二进制1的个数
解法一:右移整数
public static int num(int n){
int count=0;
while(n>0){
if((n&1)!=0)++count;
n>>=1;
}
return count;
}
解法二:左移1
public static int num1(int n){
int count=0;
int flag = 1;
while(flag>0){
if((n&flag)!=0)++count;
flag<<=1;
}
return count;
}
解法三:n = n&(n-1);//会把二进制最右边的1消掉
public static int num2(int n){
int count=0;
while(n>0){
++count;
n = n&(n-1);//会把最右边的1消掉
}
return count;
}
得到数最右边的1
public static boolean rightOne(int n){
return (n& -n);
}
数组除了两个数字其他数字都出现了两次,找到这两个数字
一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
示例 1:
输入:nums = [4,1,4,6,3,3]
输出:[1,6] 或 [6,1]
如果数组里只有一个数单独出现,其他数都出现两次,那么全部异或就可以,如果有两个数单独出现,如果我们可以把数组分成两组,一组是1,3,3;另一组是6,4,4,那么很容易可以得出1和6;关键在于如何分组,先全部异或得到sum=7,
在根据7的二进制某一位1来把数组分成两组,这里我们选择拿7的最低位1,就是1,则f=1,如果数组里的数最低位是1则分成一组,否则另一组
public int[] singleNumbers(int[] nums) {
int sum=0;
for(int num:nums){
sum^=num;
}
int f = sum&(-sum);
int[] ans = new int[2];
for(int num:nums){
if((num&f)==0){
ans[0]^=num;
}else{
ans[1]^=num;
}
}
return ans;
}
某个数是否是2的n次方(n>=0)
public static boolean isTwoPower(int n){
n = n&(n-1);//会把最右边的1消掉
return n==0;
}
public static boolean isTwoPower1(int n){
return (n& -n) == n;
}
需要改变多少位才可使两个数相等
先异或后计算异或结果的1的个数
public static int howNum(int m,int n){
int x = m^n;
return num2(x);
}
int,byte互转
public static byte[] getBytes(int n){
byte[] bytes = new byte[4];
bytes[0] = (byte) n;
bytes[1] = (byte) (n>>8);
bytes[2] = (byte) (n>>16);
bytes[3] = (byte) (n>>24);
return bytes;
}
public static int getInt(byte[] bytes){
int int1 = bytes[0]&0xff;
int int2 = bytes[1]&0xff<<8;
int int3 = bytes[2]&0xff<<16;
int int4 = bytes[3]&0xff<<24;
return int1|int2|int3|int4;
}