zoukankan      html  css  js  c++  java
  • 求一个10进制正整数转为2进制整数中0和1的个数

    这道题目一开始只想到了把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);
            }
        }
    }
  • 相关阅读:
    直线型一阶倒立摆5---硬件平台搭建
    PE view---重要参数--C语言实现
    A1132. Cut Integer
    A1131. Subway Map (30)
    A1130. Infix Expression
    A1129. Recommendation System
    A1128. N Queens Puzzle
    A1127. ZigZagging on a Tree
    A1126. Eulerian Path
    A1125. Chain the Ropes
  • 原文地址:https://www.cnblogs.com/shineyoung/p/10485869.html
Copyright © 2011-2022 走看看