Python basic algorithm training - cycle training (41~45)

41. Digit Flip
[Title Description]
Given a number n, you can perform several operations, and each operation can flip a certain bit in the binary representation of n, that is, 0 becomes 1, and 1 becomes 0.
May I ask: How many operations are needed at least to change n into n−1.
[Input]
A positive integer n. (1<n≤109)
【Output】
Output the minimum number of operations.
【Input sample】
10
【Output sample】
2

# 样例代码
n=int(input())
m=n-1
ans=0
while n:
    if n&1!=m&1 :
        ans+=1
    n>>=1
    m>>=1
print(ans)

42. Find the lowest number
[Title Description]
Give you a positive integer A (1≤A≤2.1×109), and output the lowest number of A.
For example, given you A=26, we can convert A into binary as 11010, then the lowest number of A is 10, and the decimal output of 10 is 2.
For another example, if you give A=88, we can convert A into binary as 1011000, then the lowest number of A is 1000, and the output is 8.
[Input]
The input contains multiple sets of test samples. Enter a positive integer A (1≤A≤2.1×109) in each line. When 0 is entered, the input ends.
[Output]
For each input, output the corresponding lowest number.
[Input example]
26
88
0
[Output example]
2
8

# 样例代码
while

Guess you like

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