【华为机试062】查找输入整数二进制中1的个数

题目描述:

请实现如下接口

     public   static   int  findNumberOf1( intnum)

    {

         /*  请实现  */

         return  0;

    } 譬如:输入5 ,5的二进制为101,输出2

Java实现:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int count = 0;
            /*方法1
            while (n != 0) {
                if (n % 2 == 1)
                    count++;
                n /= 2;
            }
            */
            /*方法2
             while (n != 0) {
                count += n & 1;
                n >>>= 1;
            }
            */
            /*方法3
            while (n != 0) {
                n &= (n-1);
                count++;
            }
            */
            //方法4
            while( n != 0) {
                n -= n & (~n + 1);
                count++;
            }
            System.out.println(count);
        }
    }
}

关键点:

  • 无符号右移>>>

猜你喜欢

转载自blog.csdn.net/heyiamcoming/article/details/81097351
今日推荐