AcWing 801. 二进制中1的个数(Bit operation) Described by Java

The basic algorith , bit operation.
Basic has two module .
One , (n >> k & 1) is to cal the ith of a number is 0 or 1.
For example , n = 10 = (1010)2,
so n >> 0 & 1 = 0;
n >> 1 & 1 = 1;
n >> 2 & 1 = 0;
n >> 3 & 1 = 1;
Two , (n & -n) is to cal the last 1 the number with.
For example , n = (1000101000)2 (n & -n) = (1000)2

给定一个长度为n的数列,请你求出数列中每个数的二进制表示中1的个数。

输入格式
第一行包含整数n。

第二行包含n个整数,表示整个数列。

输出格式
共一行,包含n个整数,其中的第 i 个数表示数列中的第 i 个数的二进制表示中1的个数。

数据范围
1≤n≤100000,
0≤数列中元素的值≤109
输入样例:
5
1 2 3 4 5
输出样例:
1 1 2 1 2


Use the second module .
Code :

import java.io.*;
public class Main{
    static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    static PrintWriter pw = new PrintWriter(System.out);
    static int n, nums[];
    public static void main(String args[]) throws Exception {
        st.nextToken();
        n = (int)st.nval;
        nums = new int[n];
        for (int i = 0 ; i < n ; i ++) {
            st.nextToken();
            nums[i] = (int)st.nval;
        }
        for (int i = 0; i < n ; i++ ){
            int ans = 0;
            while (nums[i] != 0) {
                nums[i] -= lowbit(nums[i]);
                ans++;
            }
            System.out.print(ans + " ");
        }
    }
    private static int lowbit(int n){
        return n & -n;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值