题解 | #求int型正整数在内存中存储时1的个数#

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

https://www.nowcoder.com/practice/440f16e490a0404786865e99c6ad91c9

位运算 n & (n - 1)

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);

        int n = Integer.parseInt(br.readLine());
        int ans = 0;
        while (n != 0) {
            ans++;
            n &= (n - 1);
        }
        pw.println(ans);

        pw.flush();
        pw.close();
        br.close();
    }
}

逐位判断

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);

        int n = Integer.parseInt(br.readLine());
        int ans = 0;
        for (int i = 0; i < 32; i++) {
            if ((n & (1 << i)) != 0) {
                ans++;
            }
        }
        pw.println(ans);

        pw.flush();
        pw.close();
        br.close();
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务