题解 | #查找输入整数二进制中1的个数#

用位运算,提高效率

import java.io.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    System.in));
        String str = "";
        while ((str = bufferedReader.readLine()) != null) {
            int i = Integer.parseInt(str);
            int count = 0;
            while (i > 0) {
                if ((i & 1) == 1) {
                    count++;
                }
                i >>= 1;
            }
            System.out.println(count);
        }
    }
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

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