Golden interview programmers - face questions 05.06 integer conversion (bit operation)

1. Topic

Integer conversion. Write a function to determine the need to change a few bits can be converted to integer integer A B.

示例1:
 输入:A = 29 (或者0b11101), B = 15(或者0b01111)
 输出:2
 
示例2:
 输入:A = 1,B = 2
 输出:2
 
提示:
A,B范围在[-2147483648, 2147483647]之间

2. Problem Solving

class Solution {
public:
    int convertInteger(int A, int B) {
        int s = A^B;//不相同的位为1
    	int count = 0;
    	for(int i = 0; i < 32; ++i)
    	{
    		if((s>>i)&1)//每个位移到最右边,跟1与,为1说明不同
    			count++;
    	}
    	return count;
    }
};

Here Insert Picture Description

Published 748 original articles · won praise 921 · views 260 000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105002871