1.编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为 汉明重量).)。
题目链接:力扣
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res =0;
while(n !=0){
res ++;
n= n&(n-1);//这里每按位与一次发现一个原n最右边的1
}
return res;
}
}
2.不用加减乘除做加法
写一个函数,求两个整数之和,要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。
题目链接: 力扣
这里使用while是因为每次产生进位,直到不产生进位时,才计算出最后和
class Solution {
public int add(int a, int b) {
//无符号加是 异或(相同为0),;进位是与+(通过左移实现);
while(b!=0){
int c = (a & b) <<1;//进位
a^=b;//无进位加
b = c;
}
return a;
}
}