7月22日:字节笔试题:
给定一个正整数n,求1到n所有正整数的二进制表示中1的个数和(leetcode上的原题,略有改动)
参考:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/solution/mian-shi-ti-43-1n-zheng-shu-zhong-1-chu-xian-de-2/
内心慌乱,当场未能想出来,如何修改~
想过后:来补一补。
class Solution:
def countDigitOne(self, n) :
digit, res = 1, 0
high, cur, low = n // 2, n % 2, 0
while high != 0 or cur != 0:
if cur == 0:
res += high * digit
else:
res += high * digit + low + 1
low += cur * digit
cur = high % 2
high //= 2
digit *= 2
return res
if __name__ == '__main__':
n = 5
sol = Solution()
end = sol.countDigitOne(n)
print(end)
给定一个正整数n,求1到n所有正整数的二进制表示中1的个数和(leetcode上的原题,略有改动)
参考:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/solution/mian-shi-ti-43-1n-zheng-shu-zhong-1-chu-xian-de-2/
内心慌乱,当场未能想出来,如何修改~
想过后:来补一补。
class Solution:
def countDigitOne(self, n) :
digit, res = 1, 0
high, cur, low = n // 2, n % 2, 0
while high != 0 or cur != 0:
if cur == 0:
res += high * digit
else:
res += high * digit + low + 1
low += cur * digit
cur = high % 2
high //= 2
digit *= 2
return res
if __name__ == '__main__':
n = 5
sol = Solution()
end = sol.countDigitOne(n)
print(end)
全部评论
相关推荐
//鲨鱼辣椒:什么什么都作废了,如同一场大雪覆盖了前半生的荒唐
点赞 评论 收藏
分享
摩天轮大盗:逆天
点赞 评论 收藏
分享