题目链接:
力扣https://leetcode-cn.com/problems/minimum-bit-flips-to-convert-number/
【分析】先用转位为二进制,然后从后向前比对,再统计较长的字符串多出来的1的个数。
class Solution:
def minBitFlips(self, start: int, goal: int) -> int:
ss = bin(start)[2:][::-1]
st = bin(goal)[2:][::-1]
m, n = len(ss), len(st)
if m > n:
m, n = n, m
ss, st = st, ss
ans, i = 0, 0
while i < m:
if ss[i] != st[i]:
ans += 1
i += 1
while i < n:
if st[i] == '1':
ans += 1
i += 1
return ans
【异或】直接将两数异或之后转为二进制统计1的个数
class Solution:
def minBitFlips(self, start: int, goal: int) -> int:
return bin(start ^ goal).count('1')
【Java版】
class Solution {
public int minBitFlips(int start, int goal) {
String str = Integer.toString(start ^ goal, 2);
int ans = 0, n = str.length();
for(int i = 0;i < n; i++){
if(str.charAt(i) == '1') ++ans;
}
return ans;
}
}