链接:https://www.nowcoder.com/questionTerminal/8ee967e43c2c4ec193b040ea7fbb10b8?answerType=1&f=discussion
来源:牛客网
public class Solution {
public int NumberOf1(int n) {
String s=Integer.toBinaryString(n);
String[] split=s.split("");
int a=0;
for(int i = 0; i < split.length; i++) {
if (split[i].equals("1"))
{
a++;
}
}
return a;
}
}
链接:https://www.nowcoder.com/questionTerminal/8ee967e43c2c4ec193b040ea7fbb10b8?answerType=1&f=discussion
来源:牛客网
public class Solution {
public int NumberOf1(int n) {
int num = 0;
while (n != 0) {
num++;
n &= (n - 1);
}
return num;
}
}
2.整数反转
class Solution {
public:
int reverse(int x) {
long res=0;
while(x!=0){
int pop=x%10;
if(res>INT_MAX/10||(res==INT_MAX/10&&pop>7))
return 0;
if(res<INT_MIN/10||(res==INT_MIN/10&&pop<-8))
return 0;
res=res*10+pop;
x/=10;
}
return res;
}
};