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  阅读(386)  评论(0编辑  收藏  举报