[Programmers / JAVA] Level 1 Reversing a Natural Number into an Array (12932)
[Programmers / JAVA] Level 1 Reversing a Natural Number into an Array (12932)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
🔗 Reversing a Natural Number into an Array
Reverse the natural number n and return it as an array containing each digit as an element. For example, if n is 12345, return [5,4,3,2,1].
- n is a natural number no greater than 10,000,000,000.
| n | return |
|---|---|
| 12345 | { 5, 4, 3, 2, 1 } |
Reverse the natural number n and return each digit as an array.
There is also a method of converting the number into a string and arranging each character in reverse order. But this time, let's solve it using numeric operations.
Declare an ArrayList to hold each digit.
JAVA
ArrayList<Integer> list = new ArrayList<>(); while (n >= 10) { list.add((int) (n % 10)); n /= 10; } list.add((int) n);
You can get the last digit with n % 10, and get the remaining number excluding that digit with n / 10. Repeat this operation until n becomes smaller than 10.
Since we obtain the digits starting from the ones place, we don't even need to reverse the array — we can just return it as it is.
JAVA
import java.util.ArrayList; /** * Reversing a Natural Number into an Array class * * @author RWB * @since 2021.12.13 Mon 18:31:27 */ class Solution { /** * Method that returns the answer * * @param n: [long] natural number * * @return [int[]] answer */ public int[] solution(long n) { ArrayList<Integer> list = new ArrayList<>(); while (n >= 10) { list.add((int) (n % 10)); n /= 10; } list.add((int) n); return list.stream().mapToInt(Integer::intValue).toArray(); } }
