首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C 語言位運算面試題:統計兩數二進制不同位數(模除法 vs 移位法)

     編輯:關於C

方法一:逐位模除法

int diffBits(int m, int n) {
    int cnt = 0;
    for (int i = 0; i < 32; ++i) {
        if ((m % 2) != (n % 2)) cnt++;
        m /= 2; n /= 2;
    }
    return cnt;
}

方法二:異或 + 移位統計(標準解法)

int diffBits(int m, int n) {
    int x = m ^ n; // 異或:相同為 0,不同為 1
    int cnt = 0;
    while (x) {
        cnt += x & 1;
        x >>= 1;
    }
    return cnt;
}

方法三:異或 + Brian Kernighan(最快)

int diffBits(int m, int n) {
    int x = m ^ n, cnt = 0;
    while (x) { x &= x-1; cnt++; }
    return cnt;
}

完整測試代碼

#include <stdio.h>

int main() {
    int m, n;
    scanf("%d %d", &m, &n);
    int x = m ^ n, cnt = 0;
    while (x) { x &= x-1; cnt++; }
    printf("不同位數: %d\n", cnt);
    return 0;
}

核心洞察

「兩數二進制不同位數」等價於「m ^ n 中 1 的個數」。先異或聚焦差異,再統計 1 的個數,是位運算面試必考套路。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved