青蛙跳臺階和驗證冪數的方法



# 一隻青蛙一次可以跳上1級臺階,也可以一次跳上2級……它也可以一次跳上n級。求該青蛙跳上一個n級的臺階總共有多少種跳法。

# 當跳1級臺階時,f(1) = 1;

# 當跳2級臺階時,f(2) = f(1) + 1 = 2;

# 當跳3級臺階時,f(3) = f(2) + f(1) + 1 = 4;

# 當跳4級臺階時,f(4) = f(3) + f(2) + f(1) + 1 = 8;

# f(n-1) = f(n-2) +...+ f(2) + f(1) + 1

# f(n) = f(n-1) + f(n-2) +...+ f(2) + f(1) + 1
#     =  f(0) + f(1) + f(2) + f(3) + ... + f(n-2)      +    f(n-1)
#     =               f(n-1)                           +    f(n-1)  = 2*f(n-1)
# 所以 f(n) = 2*f(n-1), n >=2   n=0和1時, f(n)=1


# 方法1(遞歸):
def num1(n):
    while n <= 2:
        return n

    return num1(n - 1) * 2


print(num1(15))     # 16384


# 方法2: 找規律
def num2(n):
    while n <= 2:
        return n
    return 2 ** (n - 1)     # 2, 4, 8, 16, 32


print(num2(15))     # 16384 == 2的14次冪


# 突發奇想: 如何驗證16384是2的14次冪

# 方法1:通用方法
import math
def cloth_cover(num, backgroud):
    lognum = math.log(num, backgroud)       # 求以 backgroud 的多少次冪 等於num  返回值帶小數點
    int_part = math.floor(lognum)           # math.floor 向下取整 math.ceil 向上取整
    if lognum - int_part == 0:
        print("%d是%d的%d次冪" % (num, backgroud, int_part))
    else:
        print('%d不是%d整數次冪' % (num, backgroud))


cloth_cover(16384, 2)


# 方法2:特殊方法
def judge(num):
    num = int(num)
    return True if num == 0 or num & (num - 1) == 0 else False


ret = judge(16384)
print(ret)
"""
    方法2原理:
        十進制           二進制
        0                 0
        2                 10
        4                 100
        8                 1000
        16                10000
        
        
        十進制            二進制
        1                 01
        3                 011
        7                 0111
        15                01111
        
        
       例如:16-15 == > 10000 & 01111 = > 0     
      # & : 如果相同位置,數字不同,則該位置結果爲0, 相同則爲1  
      # 具體: https://blog.csdn.net/qq_42327755/article/details/103560957
"""

 

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