shineyoung

这道题目一开始只想到了把10进制整数转为2进制数组

toBinaryString(int i) 将i以二进制形式输出出来

toOctalString(int i)将i以八进制形式输出出来

toHexString(int i)将i以十六进制形式输出出来

不过这是直接调用api并不是题目的本意

调用toBinaryString的代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()) {
            int num = in.nextInt();
            in.nextLine();
            int count = 0;
            String list = Integer.toBinaryString(num);
            for (int i = 0; i < list.length(); i++) {
                if(list.charAt(i) == \'1\') {
                    count++;
                }
            }
            
            System.out.println(count);
        }
    }
}

求1的个数

使用&运算判断尾巴有没有1有的话去掉再判断

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()) {
            int num = in.nextInt();
            in.nextLine();
            int count = 0;
            while(num != 0) {
                if((num & 1) == 1) {
                    count++;
                }
                num = num/2;
            }
            System.out.println(count);
        }
    }
}

 

使用%判断尾巴有没有0,有的话去掉再判断

求0的个数

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()) {
            int num = in.nextInt();
            in.nextLine();
            int count = 0;
            while(num != 0) {
                if((num % 2) == 0) {
                    count++;
                }
                num = num/2;
            }
            System.out.println(count);
        }
    }
}

 

 

posted on 2019-03-06 20:43  ShineYoung  阅读(327)  评论(0编辑  收藏  举报

分类:

技术点:

相关文章:

  • 2021-11-01
  • 2021-08-09
  • 2021-05-05
  • 2022-02-15
  • 2022-12-23
  • 2022-12-23
  • 2021-11-03
  • 2022-12-23
猜你喜欢
  • 2021-07-04
  • 2022-03-15
  • 2021-11-15
  • 2022-03-15
  • 2021-04-19
  • 2021-07-15
  • 2021-09-21
相关资源
相似解决方案