解题思路
这是一个位运算问题,可以通过以下步骤解决:
- 
使用异或运算(XOR): - 两个数字异或后,相同位为 ,不同位为 
- 只需要统计异或结果中 的个数 
 
- 两个数字异或后,相同位为 
- 
统计1的个数方法: - 使用位运算 消除最低位的 
- 或使用内置函数如 
 
- 使用位运算 
代码
#include <iostream>
using namespace std;
int countBits(int n) {
    int count = 0;
    while(n) {
        n &= (n-1);  // 消除最低位的1
        count++;
    }
    return count;
}
int main() {
    int m, n;
    cin >> m >> n;
    
    // 异或后统计1的个数
    cout << countBits(m ^ n) << endl;
    return 0;
}
import java.util.*;
public class Main {
    public static int countBits(int n) {
        int count = 0;
        while(n != 0) {
            n &= (n-1);  // 消除最低位的1
            count++;
        }
        return count;
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        
        // 异或后统计1的个数
        System.out.println(countBits(m ^ n));
    }
}
def count_bits(n):
    count = 0
    while n:
        n &= (n-1)  # 消除最低位的1
        count += 1
    return count
def main():
    m, n = map(int, input().split())
    
    # 异或后统计1的个数
    print(count_bits(m ^ n))
if __name__ == "__main__":
    main()
算法及复杂度
- 算法:位运算
- 时间复杂度:,其中 为数字的大小 
- 空间复杂度:

 京公网安备 11010502036488号
京公网安备 11010502036488号