求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);
    }
}
全部评论

相关推荐

03-11 16:05
运城学院 Java
程序员小白条:简历内容太多了,而且一段实习都没的情况下,写这么多,没啥说服力,反而让人觉得假
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
03-02 08:18
集美大学 Java
钱嘛数字而已:没有赛事奖项么?另外,项目经历字有点多哈,建议突出一下重点:用的什么技术,解决什么问题,达到什么效果。
大家都开始春招面试了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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