如何在 Android Studio 中对数字进行排序?

How to sort numbers in Android Studio?

如何将每个数字放入一个变量中,例如,我有 2118,我想要这个:

不知道号码怎么办?

int abcd = 2118;
int a = 8;
int b = 10;
int c = 100;
int d = 2000;

或者

int abcd = 2118;
int a = 8; // 8
int b = 1; // 10
int c = 1; // 100
int d = 2; //2000

我会使用模数运算符来完成(我认为)您要问的事情。

像这样...

 int num=1351280;
 int ones = (num % 10)/1;
 int tens = (num-ones) % 100;
 int hun = (num-(tens+ones)) % 1000;
 int thou = (num-(tens+ones+hun)) % 10000;
 int tenThou = (num-(tens+ones+hun+thou)) % 100000;
 int hunThou = (num-(tens+ones+hun+thou+tenThou)) % 1000000;
 int mil  = (num-(tens+ones+hun+thou+tenThou+hunThou)) % 10000000;

 System.out.println(mil);
 System.out.println(hunThou);
 System.out.println(tenThou);
 System.out.println(thou);
 System.out.println(hun);
 System.out.println(tens);
 System.out.println(ones);

这给出:

1000000 (Millions)
300000  (Hundred thousands)
50000   (Ten thousands)
1000    (Thousands)
200     (Hundreds)
80      (Tens)
0       (Ones)

模数运算符给出余数,所以 30 % 8 = 6 类似于 (30/8) = 3。而 30-(3*8) = 6;

是否可以转换为 String 然后使用 String#toCharArray() 最后进行反向循环。

String num = String.valueOf(someInt);
char[] dig = num.toCharArray();
char[] reverse = new char[dig.length()];
int j = 0;
for(int i=reverse.length-1; i>=0; i--) {
    reverse[j] = dig[i];
    j++;
}

您应该更喜欢递归计算数字;

示例代码

package com.levo.so.digits;

public class DigitDisplay {

    public static void main(String[] args) {
        int number = 2118;

        System.out.println("Number : " + number);
        System.out.println();

        int[] digits = getDigitArray(number);


        System.out.println("Digits;");
        System.out.println("-------");
        for(int i = 0; i < digits.length; i++) {
            System.out.printf("Digit [%d]: %d\n", i, digits[i]);
        }

        System.out.println("\n");

        System.out.println("Components");
        System.out.println("----------");
        for(int i = 0; i < digits.length; i++) {
            System.out.printf("[%d]: %d\n", i, digits[i]*(int)Math.pow(10, i));
        }
    }

    private static int[] getDigitArray(int number) {
        int[] array = new int[getDigitCount(number)];

        int index = 0;
        while(number != 0) {
            array[index++] = (number%10);
            number /= 10;
        }

        return array;
    }

    private static int getDigitCount(int number) {
        int digitCount = 0;

        while(number != 0) {
            number /= 10;
            digitCount++;
        }

        return digitCount;
    }

}

输出

Number : 2118

Digits;
-------
Digit [0]: 8
Digit [1]: 1
Digit [2]: 1
Digit [3]: 2


Components
----------
[0]: 8
[1]: 10
[2]: 100
[3]: 2000