1. 程式人生 > >FinixLei的專欄 (https://github.com/FinixLei)

FinixLei的專欄 (https://github.com/FinixLei)

看到某公司2018的校招筆試題,手癢做了一下。非常簡單,數分鐘可以搞定。但是也要細心一點,因為也會有些小坑。題目大意是:寫一個函式,實現除法,返回整數結果和餘數,要求演算法複雜度o(lgN).

5分鐘寫完基本程式,即正數的除法。後來想起來還有負數和0的情況,又改了一下。也許程式還能再簡潔點。

def div(a, b):
    def _simple_div(a, b):  # Here, both a and b are positive
        if a < b: 
            return 0, b

        last_x = x = 1
        while x * b < a:
            last_x = x
            x *= 2
        
        if x * b == a:
            return x, 0
        else:
            return last_x, a-last_x*b 
            
    if b == 0:
        raise Exception("Wrong. b cannot be zero!")
    if a == 0:
        return 0,0
        
    if a > 0 and b < 0:
        b = -b 
        flag = '+-'
    elif a < 0 and b < 0:
        a = -a 
        b = -b 
        flag = '--'
    elif a < 0 and b > 0:
        a = -a
        flag = '-+'
    else: 
        flag = '++'

    final_result, rest = _simple_div(a, b) 
    while rest != 0 and rest > b:
        result, rest = _simple_div(rest, b)
        final_result += result 
        
    if flag == '--':
        rest = -rest 
    elif flag == '-+':
        final_result = -final_result 
        rest = -rest 
    elif flag == '+-':
        final_result = -final_result 
    else: 
        pass     
    return final_result, rest
        
def test(a, b):
    c, d = div(a, b)
    print("%s / %s = %s...%s" % (a, b, c, d))


test(100, 10)
test(100, 9)
test(10, 100)
test(16, 9)
test(567, 38)
test(33, 33)
test(7, 3)
test(-7, -3)
test(7, -3)
test(-7, 3)
test(10, -1)
test(-999, 456)
test(0, -100)
test(0, 99)
test(10, 0)

(完)