Leetcode sumary: Math problem

29. Divide Two Integers

class Solution(object):
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        if (dividend == -2147483648 and divisor==-1) or divisor==0:
            return 2147483647
        
        sign=0
        if (dividend>=0 and divisor>0) or (dividend<=0 and divisor<0):
            sign=1
        else:
            sign=-1
    
        #sign=(dividend<0) is (divisor<0)
        m=abs(dividend)
        n=abs(divisor)
        
        ret=0
        while m>=n:
            t=n
            p=1
            while m>=t<<1:
                t=t<<1
                p=p<<1
            ret=ret+p
            m=m-t           
            
        if sign==-1:
            return -ret
        
        return ret

中文數字轉換成阿拉伯數字

def convertChineseDigitsToArabic (chinese_digits, encoding="utf-8"):
    if isinstance (chinese_digits, str):
        chinese_digits = chinese_digits.decode (encoding)

    print chinese_digits,len(chinese_digits)
    result  = 0
    tmp     = 0
    hnd_mln = 0
    for count in range(len(chinese_digits)):
        curr_char  = chinese_digits[count]
        curr_digit = chs_arabic_map.get(curr_char, None)
        # meet 「億」 or 「億」
        if curr_digit == 10 ** 8:
            result  = result + tmp
            result  = result * curr_digit
            # get result before 「億」 and store it into hnd_mln
            # reset `result`
            hnd_mln = hnd_mln * 10 ** 8 + result
            result  = 0
            tmp     = 0
        # meet 「萬」 or 「萬」
        elif curr_digit == 10 ** 4:
            
            result = result + tmp
            result = result * curr_digit
            tmp    = 0
        # meet 「十」, 「百」, 「千」 or their traditional version
        elif curr_digit >= 10:
            tmp    = 1 if tmp == 0 else tmp
            result = result + curr_digit * tmp
            tmp    = 0
        # meet single digit
        elif curr_digit is not None:
            tmp = tmp * 10 + curr_digit
            print tmp

        else:
            return result
    result = result + tmp
    result = result + hnd_mln
    return result


print convertChineseDigitsToArabic("十一萬三千六百二十一")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章