《剑指offer》Python版

16数值的整数次方

2018-11-17  本文已影响0人  gantrol

实现函数exp(base, expo),求base的expo次方。不得使用库函数,同时不需要考虑大数问题。


def exp(base, expo):
    if expo == 0: return 1
    elif expo == 1: return base
    elif expo < 0:
        return 1 / exp(base, -expo)

    # if expo % 2 == 0:
    #     return exp(base, expo / 2) * exp(base, expo / 2)
    # elif expo % 2 == 1:
    #     return exp(base, (expo - 1) / 2) * exp(base, (expo - 1) / 2) * exp(base, 1)
    
    result = exp(base, expo >> 1)
    result *= result
    if expo & 0x1 == 1:
        result *= base
    return result

if __name__ == '__main__':
    assert exp(3, -1) == 0.3333333333333333
    assert exp(3, 10) == 59049
    assert exp(2, -3) == 0.125
    assert exp(2, 0) == 1
    assert exp(0, 0) == 1
    assert exp(0, 1) == 0
    assert exp(3, 0) == 1
上一篇下一篇

猜你喜欢

热点阅读