Output each bit of an integer

Ideas:

  • For example, input 123, first determine that there are 3 digits (the second digit, the first digit, the 0th digit)
  • Take out each bit in turn from high to low
  • Take out the highest bit 1, that is, 123/100=1; in order to take out the next bit, update the number, 123%100=23
  • Take out the next bit 2, that is, 23/10=2; in order to take out the next bit, update the number, 23%10=3
  • Take out the last digit 3, that is, 3/1=3
  • Among them, 100, 10, and 1 are 10^2, 10^1, 10^0 respectively. Take out the number of digits, which is the power of /10 (the second place, the first place, and the zeroth place)

Code:

import java.util.Scanner;

public abstract class pra1214 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        int num = sc.nextInt();
        System.out.println(num + "的每一位是");
        everyPosition(num);
    }

    //首先看有多少位
    //再取出每一位输出
    public static void everyPosition(int num) {
        int num1 = num;
        int count = 0;
        while (num1 != 0) {
            num1 = num1 / 10;
            count++;
        }
        for (int i = count - 1; i >= 0; i--) {
            if (i != 0) {
                System.out.print(num / (ciFang(i)) + ",");
                num = num % (ciFang(i));

            } else {
                System.out.println(num / (ciFang(i)));
            }
        }
    }
    //10的i次方
    public static int ciFang(int i) {
        if (i == 0) {
            return 1;
        }
        int num = 1;
        for (int j = 1; j <= i; j++) {
            num *= 10;
        }
        return num;
    }
}

operation result:

 

Guess you like

Origin blog.csdn.net/weixin_43939602/article/details/111941276