牛客题解 | 两个整数二进制位不同个数
题目
解题思路
这是一个位运算问题,可以使用异或运算(XOR)来解决。两个数字异或后,结果中1的个数就是原数字对应位不同的个数。
关键点:
- 使用异或运算找出不同的位
- 计算二进制中1的个数
- 使用位运算优化计数过程
算法步骤:
- 对两个数进行异或运算
- 统计异或结果中1的个数
代码
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    int countDifferentBits(int a, int b) {
        // 异或运算找出不同的位
        int xorResult = a ^ b;
        
        // 计算1的个数
        int count = 0;
        while (xorResult) {
            count += xorResult & 1;
            xorResult >>= 1;
        }
        
        return count;
    }
};
int main() {
    int a, b;
    cin >> a >> b;
    
    Solution solution;
    cout << solution.countDifferentBits(a, b) << endl;
    
    return 0;
}
import java.util.*;
public class Main {
    static class Solution {
        public int countDifferentBits(int a, int b) {
            // 异或运算找出不同的位
            int xorResult = a ^ b;
            
            // 计算1的个数
            int count = 0;
            while (xorResult != 0) {
                count += xorResult & 1;
                xorResult >>>= 1;  // 使用无符号右移
            }
            
            return count;
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        
        Solution solution = new Solution();
        System.out.println(solution.countDifferentBits(a, b));
        
        sc.close();
    }
}
class Solution:
    def count_different_bits(self, a: int, b: int) -> int:
        # 异或运算找出不同的位
        xor_result = a ^ b
        
        # 计算1的个数
        count = 0
        while xor_result:
            count += xor_result & 1
            xor_result >>= 1
        
        return count
# 读取输入
a, b = map(int, input().split())
solution = Solution()
print(solution.count_different_bits(a, b))
算法及复杂度
- 算法:位运算
- 时间复杂度:\(O(\log n)\),其中 \(n\)是输入数字的大小
- 空间复杂度:\(O(1)\)
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号