校招算法笔面试 | 校招笔面试真题-两个整数二进制位不同个数

题目

题目链接

解题思路

这是一个位运算问题,可以使用异或运算(XOR)来解决。两个数字异或后,结果中1的个数就是原数字对应位不同的个数。

关键点:

  1. 使用异或运算找出不同的位
  2. 计算二进制中1的个数
  3. 使用位运算优化计数过程

算法步骤:

  1. 对两个数进行异或运算
  2. 统计异或结果中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 ) O(\log n) O(logn),其中 n n n是输入数字的大小
  • 空间复杂度: O ( 1 ) O(1) O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值