[编程题]求int型正整数在内存中存储时1的个数

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

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

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int num = sc.nextInt();
            //计算1的个数
            int count = 0;
            String toBinary = Integer.toBinaryString(num);
            for(int i = 0; i < toBinary.length(); i++){
                char c = toBinary.charAt(i);
                if(c == '1'){
                    count++;
                }
            }
            System.out.println(count);
        }
    }
}
全部评论
转换成字符串,s.length()-s.replaceAll("1").lengrh(),计算长度
1 回复 分享
发布于 2021-05-19 19:02

相关推荐

程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
LastWh1spe...:ssob真有些人和那个没睡醒一样
点赞 评论 收藏
分享
评论
22
3
分享

创作者周榜

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