[java] int 숫자의 별도 숫자를 얻는 방법은 무엇입니까?

1100, 1002, 1022 등의 숫자가 있습니다. 예를 들어 첫 번째 숫자 1100의 경우 1, 1, 0, 0과 같이 개별 숫자를 갖고 싶습니다.

Java로 어떻게 구할 수 있습니까?



답변

이렇게하려면 %(mod) 연산자를 사용합니다 .

int number; // = some int

while (number > 0) {
    print( number % 10);
    number = number / 10;
}

mod 연산자는 숫자에 대한 int 나누기의 나머지를 제공합니다.

그래서,

10012 % 10 = 2

때문에:

10012 / 10 = 1001, remainder 2

참고 : Paul이 지적한대로이 번호는 역순으로 표시됩니다. 스택에 밀어 넣고 반대 순서로 튀어 나와야합니다.

숫자를 올바른 순서로 인쇄하는 코드 :

int number; // = and int
LinkedList<Integer> stack = new LinkedList<Integer>();
while (number > 0) {
    stack.push( number % 10 );
    number = number / 10;
}

while (!stack.isEmpty()) {
    print(stack.pop());
}


답변

로 변환 String하고 사용 String#toCharArray()또는 String#split().

String number = String.valueOf(someInt);

char[] digits1 = number.toCharArray();
// or:
String[] digits2 = number.split("(?<=.)");

경우에 당신은 이미 자바 (8)에이야 그리고 당신은, 나중에 그 일부 집계 작업을 수행 할 일이 사용을 고려 String#chars()얻을 IntStream그것의 아웃.

IntStream chars = number.chars();


답변

이건 어때요?

public static void printDigits(int num) {
    if(num / 10 > 0) {
        printDigits(num / 10);
    }
    System.out.printf("%d ", num % 10);
}

또는 콘솔로 인쇄하는 대신 정수 배열로 수집 한 다음 배열을 인쇄 할 수 있습니다.

public static void main(String[] args) {
    Integer[] digits = getDigits(12345);
    System.out.println(Arrays.toString(digits));
}

public static Integer[] getDigits(int num) {
    List<Integer> digits = new ArrayList<Integer>();
    collectDigits(num, digits);
    return digits.toArray(new Integer[]{});
}

private static void collectDigits(int num, List<Integer> digits) {
    if(num / 10 > 0) {
        collectDigits(num / 10, digits);
    }
    digits.add(num % 10);
}

숫자 순서를 최하위 (index [0])에서 최상위 (index [n])로 유지하려면 다음 업데이트 된 getDigits ()가 필요합니다.

/**
 * split an integer into its individual digits
 * NOTE: digits order is maintained - i.e. Least significant digit is at index[0]
 * @param num positive integer
 * @return array of digits
 */
public static Integer[] getDigits(int num) {
    if (num < 0) { return new Integer[0]; }
    List<Integer> digits = new ArrayList<Integer>();
    collectDigits(num, digits);
    Collections.reverse(digits);
    return digits.toArray(new Integer[]{});
}


답변

아무도이 방법을 사용하는 것을 보지 못했지만 나에게 효과적이며 짧고 달콤합니다.

int num = 5542;
String number = String.valueOf(num);
for(int i = 0; i < number.length(); i++) {
    int j = Character.digit(number.charAt(i), 10);
    System.out.println("digit: " + j);
}

출력됩니다 :

digit: 5
digit: 5
digit: 4
digit: 2


답변

Java 8 스트림을 사용하여 문제를 해결하는 예는 거의 없지만 이것이 가장 간단한 것으로 생각합니다.

int[] intTab = String.valueOf(number).chars().map(Character::getNumericValue).toArray();

명확하게 : String.valueOf(number)int를 String으로 변환 한 다음 chars()IntStream을 얻는 방법 (문자열의 각 문자는 이제 Ascii 숫자 임) map()을 사용하여 Ascii 숫자의 숫자 값을 얻으려면 method를 실행해야합니다 . 마지막에 toArray()메소드를 사용하여 스트림을 int [] 배열로 변경하십시오.


답변

모든 대답이보기 흉하고 깨끗하지 않습니다.

문제를 해결하기 위해 약간의 재귀 를 사용하는 것이 좋습니다 . 이 게시물은 매우 오래되었지만 향후 코더에게 도움이 될 수 있습니다.

public static void recursion(int number) {
    if(number > 0) {
        recursion(number/10);
        System.out.printf("%d   ", (number%10));
    }
}

산출:

Input: 12345

Output: 1   2   3   4   5 


답변

// could be any num this is a randomly generated one
int num = (int) (Math.random() * 1000);

// this will return each number to a int variable
int num1 = num % 10;
int num2 = num / 10 % 10;
int num3 = num /100 % 10;

// you could continue this pattern for 4,5,6 digit numbers
// dont need to print you could then use the new int values man other ways
System.out.print(num1);
System.out.print("\n" + num2);
System.out.print("\n" + num3);