Python basic algorithm training - cycle training (36~40)

36. Bitcoin Coin
[Description]
Try to compile a program to output all integers between 0 and 15 and the corresponding decimal numbers.
【Input】
None
【Output】
Every line outputs all the integers between and the corresponding decimal numbers).
[Input example]
None
[Output example]
0000B 0
0001B 1
0010B 2
0011B 3
0100B 4
0101B 5
0110B 6
0111B 7
1000B 8
1001B 9 1010B 10 1011B 11 1100B 12 110 1B
13 1110B 14 1111B 15




# 样例代码
for i in range(16):
    s=bin(i)
    s=int(s[2:])
    print("%04dB %d"%(s,i))

37. Number of 1s
【Description】
Given a decimal non-negative integer N, find the number of 1s in the corresponding binary number.
[Input]
The input contains one line, including a non-negative integer N. (N≤10^9 )
[Output]
Output one line, including an integer, indicating the number of 1s in the binary representation of N.
【Input sample】
100
【Output sample】
3

# 样例代码
n=int(input())
ans=0
while n:
    t=1 if n%2!=0 else 0
    ans+=t
    n//=2
print(ans)

Guess you like

Origin blog.csdn.net/lybc2019/article/details/131399183