Split integer into digits array

Split integer into digits array

Hard Java Data Types 29 views
Explanation Complexity

Problem Statement

Task: return digits of a non-negative number in correct order.

Input Format

A non-negative integer n.

Output Format

An array/list of digits in correct order.

Example

5073
[5, 0, 7, 3]

Constraints

• n ≥ 0

• Must preserve digit order

Concept Explanation

Digits should appear in the same order as in the number.
We extract digits and then reverse them (since extraction gives reverse order).

Step-by-Step Explanation

1.Read integer n.

2.If n == 0, return [0].

3.Create an empty list.

4.While n > 0:

• Extract digit using n % 10.

• Add digit to list.

• Divide n = n / 10.

5.Reverse the list (because digits were added in reverse order).

6.Return the list.

Concept Explanation

Digits should appear in the same order as in the number.
We extract digits and then reverse them (since extraction gives reverse order).

Step-by-Step Explanation

1.Read integer n.

2.If n == 0, return [0].

3.Create an empty list.

4.While n > 0:

• Extract digit using n % 10.

• Add digit to list.

• Divide n = n / 10.

5.Reverse the list (because digits were added in reverse order).

6.Return the list.

Input / Output Format

Input Format
A non-negative integer n.
Output Format
An array/list of digits in correct order.
Constraints
• n ≥ 0

• Must preserve digit order

Examples

Input:
5073
Output:
[5, 0, 7, 3]

Example Solution (Public)

Java
static int[] digits(int n){if(n==0) return new int[]{0};int x=n;int len=0;while(x>0){len++;x/=10;}int[] d=new int[len];x=n;for(int i=len-1;i>=0;i--){d[i]=x%10;x/=10;}return d;}

Official Solution Code

static int[] digits(int n){if(n==0) return new int[]{0};int x=n;int len=0;while(x>0){len++;x/=10;}int[] d=new int[len];x=n;for(int i=len-1;i>=0;i--){d[i]=x%10;x/=10;}return d;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.