Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
给出一个十进制数,问其二进制表示通过以下两种操作几次可以变成0

1. Change the rightmost (0th) bit in the binary representation of n.
2. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.

很妙的思路参考 -> https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/solutions/2273798/easy-to-understand-6-line-solution-with-explanation-o-n-time-o-1-space/?envType=daily-question&envId=2023-11-30


 1 #1611
 2 #Runtime: 17 ms (Beats 66.67%)
 3 #Memory: 13.4 MB (Beats 33.33%)
 4 
 5 class Solution(object):
 6     def minimumOneBitOperations(self, n):
 7         """
 8         :type n: int
 9         :rtype: int
10         """
11         binary = format(n, "b")
12         ans = 0
13         for i in xrange(1, len(binary) + 1):
14             if binary[-i] == "1":
15                 ans = 2**i - 1 - ans
16         return ans

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理