求int型正整数在内存中存储时1的个数

求int型正整数在内存中存储时1的个数

http://www.nowcoder.com/questionTerminal/440f16e490a0404786865e99c6ad91c9

方法1:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);

        int res=0;
        int x=sc.nextInt();
        while (x!=0){
            if ((x&1)==1){
                res++;
            }
            x=x>>1;
        }

        System.out.println(res);
    }
}

方法2:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);

        int res=0;
        int x=sc.nextInt();
        String s=Integer.toBinaryString(x);
        for (int i=0;i<s.length();i++){
            if (s.charAt(i)=='1'){
                res++;
            }
        }

        System.out.println(res);
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
12-17 17:40
点赞 评论 收藏
分享
11-04 19:05
已编辑
东莞城市学院 单片机
不知道怎么取名字_:你这个要实习两年?哪有这么久的,感觉就是即使你毕业了,但还按实习的话,是不是不用给你缴社保公积金啥的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务