1.给定一个无符号32位整数N,求N的二进制表示法中含1的个数
此题是整数,不考虑负数情况,以下四种方法均可,由于是无符号32位,所以int不符合,要使用long类型
法一:取余,但对于负数不适用
输入:-1
输出:0
输入:8
输出:1
import java.util.Scanner;
public class Member {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long n = sc.nextLong();
int count=0;
while (n!=0){
int temp=n%2;
if(temp==1){
count++;
}
n=n/2;
}
System.out.println(count);
}
}
法二:二进制移位,不能让数据改变,只能拿0x01从右边每一位向左去试
输入:-1
输出:32
输入:8
输出:1
import java.util.Scanner;
public class Member2 {
public static int a = 0x01f;
public static void main(String []args){
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
int ans = 0;
long mark = 1;
while (mark != 0) {
if ((mark & n)!=0) {
++ans;
}
mark <<= 1;
}
System.out.println(ans);
}
}
法三:对于上一种解法中,无用操作是,如果当前位是0
, 还是会做判断,然后一位一位的移动。如果,给你一种超能力