Code Interview Note
  • 0. Introduction
  • 1. Basic
    • Python Basic
    • Java Basic
    • Primitive Type
    • Basic Question
    • Number
  • 2. Array and Numbers
    • General
    • TwoSum
    • Buy and Sell Stock
    • SubArray
      • SubArray + HashMap
    • Sliding Window
      • Sliding Window At Most Problem
    • Word Break
    • Passes Problem
    • Majority Element
    • Partition Array
    • Sort Colors
    • Anagram
    • Ugly Number
    • TwoPointer
    • Swipe Line
    • Calculator
    • Sudoku
  • 2.1 String
    • String
    • Palindrome
    • Parentheses
    • Decode String
    • Calculator
    • Abbreviation
  • 3. Linkedlist
    • Dummy Node
    • Double Pointers
  • 4. Stack and Queue
    • General
    • Increase/Decrease Stack
  • 5. Binary Search
    • General
    • BS on result
    • Save the half which has result
    • Rotated Sorted Array
    • Split Array Largest Sum
  • 6. Binary Tree
    • General
    • Path Sum
    • Lowest Common Ancestor
    • BST
    • Convert
    • Traverse
    • Valid Ordered Tree
    • Construct Binary Tree
    • Tree depth and width
    • Vertical Order Traverse
  • 7. Heap
    • Geneal
    • TopK
  • 8. Simulation
    • General
    • Read4
    • Encode Decode
    • LRU/LFU
    • Robot
    • GetRandom O(1)
    • Probability
  • 9. DFS
    • Backtrack
    • General
    • Subset
    • Permutation
    • Combination
  • 10. HashTable
    • General
  • 11. Sort
    • General
  • 12. Recursion
    • General
  • 13. Dynamic Programming
    • Graph
    • General
    • Coordinate
    • Double Sequence
    • Longest Common Subsequence
    • Rolling Array
    • House Robber
    • Backpack
    • Memorization
    • Diagonal
  • 14. BFS
    • General
    • Number of Islands
    • The Maze
  • 15. Graph
    • Shortest Path
    • Undirected Graph
    • Topology Sort
    • Word Ladder
    • Tarjan's Algo
  • 16. Divide & Conquer
    • General
  • 17. UnionFind
    • General
    • Grouping
  • 18. Trie
    • General
    • Word Square
  • 19. Company Summary
    • Oracle
    • Amazon
      • DP
    • Google
    • Hackerrank
    • LinkedIn
  • 20. Design
  • 21. Math
  • Behavior Question
  • Internet
  • OS
Powered by GitBook
On this page
  • 進制轉換
  • 13. Roman to Integer
  • 12 Integer to Roman
  • 8. String to Integer(atoi)
  • 50. Pow(x, n)
  • 69. Sqrt
  • 273 Integer to English Word

Was this helpful?

  1. 1. Basic

Number

進制轉換

10進位 integer to string %10 /10

Given integer n

int[] digits
int len
while(len > 0){
    digits[len--] = n%10;
    n/=10;
}

13. Roman to Integer

Given a roman numeral, convert it to an integer.

The answer is guaranteed to be within the range from 1 to 3999.

  • 7 characters

  • Add number from left to right

  • Test if left char is smaller than cur char

def romanToInt(self, s: str) -> int:
    dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
    num = dic[s[0]]
    
    for i in range(1, len(s)):
        num += dic[s[i]]
        if dic[s[i]] > dic[s[i-1]]:
            num -= dic[s[i-1]]*2

    return num

12 Integer to Roman

Given an integer, convert it to a roman numeral.

The number is guaranteed to be within the range from 1 to 3999.

  • 13 strings

  • 倍數數字 = 該roman number 重複數

def intToRoman(self, num: int) -> str:
    intList = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
    romanList = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
    
    ans = ''
    
    for i in range(13):
        while num >= intList[i]:
            ans += romanList[i]
            num -= intList[i]
            
    return ans

8. String to Integer(atoi)

  • Leetcode 8

  • Use long store

  • The number could be bigger than Long

def myAtoi(self, str: str) -> int:
    str = str.strip(' ')
    
    num = 0
    isNeg = False
    
    for c in str:
        if not c.isdigit(): 
            if c == '-': isNeg = True
            continue
        
        if not isNeg:
            if (num > (2**31)//10) or (num == 2**31//10 and int(c) > 7): return 2**31-1
        if isNeg:
            if (num > (2**31)//10) or (num == 2**31//10 and int(c) > 8): return -2**31
        num = num*10 + int(c)
        
    return num if not isNeg else -num 

50. Pow(x, n)

def myPow(self, x: float, n: int) -> float:
    if n == 0: return 1
    isExpPositive = True
    if n < 0: 
        n = -n
        isExpPositive = False
        
    num = 1
        
    while n :
        if n%2:
            num *= x 
        x *= x
        n = int(n/2)

    return num if isExpPositive else 1/num

69. Sqrt

def mySqrt(self, x: int) -> int:
    if x < 2:
        return x
    
    start, end = 2, x//2 - 1
    
    while start < end:
        mid = (start + end)//2
        if mid**2 > x:
            end = mid 
        elif mid**2 < x:
            start = mid + 1
        else:
            return mid
    
    return start - 1

273 Integer to English Word

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

def numberToWords(self, num: int) -> str:
    LESS_THAN_20 = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve','Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
    TEN = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
    THOUSAND = ['Billion', 'Million', 'Thousand', '']
    INDEX = [1000000000, 1000000, 1000, 1]
    
    def helper(num):
        if num < 20: 
            return LESS_THAN_20[num]
        elif num < 100: 
            # 注意要判斷helper回傳是否為空
            n = helper(num%10)
            return TEN[num//10] + ' ' + n if n else TEN[num//10]
        else:
            n = helper(num%100)
            return LESS_THAN_20[num//100] + ' Hundred ' + n \
                if n else LESS_THAN_20[num//100] + ' Hundred'
        
    if num == 0: return 'Zero'
    result = ''
    
    for i in range(len(INDEX)):
        if num//INDEX[i] == 0: continue
        result += helper(num//INDEX[i]) + ' ' + THOUSAND[i] + ' '
        num %= INDEX[i]
        
    return result.strip()
PreviousBasic QuestionNext2. Array and Numbers

Last updated 4 years ago

Was this helpful?