Flip Bits – Lintcode Java | Welkin Lan
Determine the number of bits required to flip if you want to convert integer n to integer m.
http://www.ithao123.cn/content-10354641.html
public static int bitSwapRequired(int a, int b) { int c = a ^ b; int count = 0; if (c < 0) { count++; c = Integer.MIN_VALUE ^ c; //??? } while(c != 0) { count += c%2; c = c/2; } return count; }
Read full article from Flip Bits – Lintcode Java | Welkin Lan
Determine the number of bits required to flip if you want to convert integer n to integer m.
Example
Given n =
31
(11111), m = 14
(01110), return 2
.
Note
Both n and m are 32-bit integers.
public static int bitSwapRequired(int a, int b) {
if (a == b) {
return 0;
}
int bit = a ^ b;
int count = 0;
// integer has 32 bits
int number = 32;
// you cannot just check bit > 0 in the while statement
// because a or b maybe negative number
while (number > 0) {
count += bit & 1;
bit = bit >> 1;
number--;
}
return count;
}
public static int bitSwapRequired(int a, int b) { int c = a^b; int count = 0; while(c!=0){ count += c&1; c=c>>>1; } return count; }
public static int bitSwapRequired(int a, int b) { int c = a^b; int count = 0; while(c!=0){ c = c&(c-1); count++; } return count; }
public static int bitSwapRequired(int a, int b) { // write your code here int count=0; while(a!=0 || b!=0){ int ai = a&1; int bi = b&1; if(ai==1 && bi==0 || ai==0 && bi==1) count++; a = a>>>1; b = b>>>1; } return count; }http://sidbai.github.io/2015/06/18/Flip-Bits/
int bitSwapRequired(int a, int b) { int ret = a ^ b; ret = ((ret & 0xaaaaaaaa) >> 1) + (ret & 0x55555555); ret = ((ret & 0xcccccccc) >> 2) + (ret & 0x33333333); ret = ((ret & 0xf0f0f0f0) >> 4) + (ret & 0x0f0f0f0f); ret = ((ret & 0xff00ff00) >> 8) + (ret & 0x00ff00ff); ret = ((ret & 0xffff0000) >> 16) + (ret & 0x0000ffff); return ret; }http://blog.csdn.net/wutingyehe/article/details/46635767
public static int bitSwapRequired(int a, int b) { int c = a ^ b; int count = 0; if (c < 0) { count++; c = Integer.MIN_VALUE ^ c; //??? } while(c != 0) { count += c%2; c = c/2; } return count; }
Read full article from Flip Bits – Lintcode Java | Welkin Lan