1 class Solution:
 2     def integerReplacement(self, n: int) -> int:
 3         count = 0
 4         while n != 1:
 5             if (n & 1) == 0: # 偶数直接右移
 6                 n >>= 1
 7             else:
 8                 n += -1 if (n & 2) == 0 or n == 3 else 1  # 奇数01或者3减一,其他加1
 9             count += 1
10         return count

算法类型:位运算。数学技巧类型的题目,看一看解答,扩展一下思路。

参考:https://leetcode-cn.com/problems/integer-replacement/solution/wei-yun-suan-by-ma-xing/

posted on 2020-04-09 09:41  Sempron2800+  阅读(133)  评论(0编辑  收藏  举报