JZ15 二进制中1的个数
二进制中1的个数
https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8?tpId=265&rp=1&ru=%2Fexam%2Foj%2Fta&qru=%2Fexam%2Foj%2Fta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D13&difficulty=&judgeStatus=&tags=&title=&gioEnter=menu
编程打卡第三天:
解法1:分情况讨论,用bin()
def NumberOf1(self , n: int) -> int:
# write code here
result = 0
result_neg = 0
if n >= 0:
binary_n = bin(n)
for strs in str(binary_n):
if strs == '1':
result += 1
return result
if n < 0:
binary_n_neg = bin(abs(n))[2:]
for strs in str(binary_n_neg):
if strs == "0":
result_neg += 1
result = 32- result_neg
return result
解法2: 反码:n & 0xffffffff
def NumberOf1(self , n: int) -> int:
# write code here
# -*- coding:utf-8 -*-
# write code here
if n < 0:
n = n & 0xffffffff
binNum = bin(n)[2:]
arr = str(binNum)
res = 0
for ch in arr:
if int(ch) == 1:
res += 1
return res