How to Convert a Number to Reversed Array of Digits in Java


The challenge

Given a random non-negative number, you have to return the digits of this number within an array in reverse order.

Test cases

import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;

public class DigitizeExampleTests {
  @Test
  public void tests() {
    assertArrayEquals(new int[] {1, 3, 2, 5, 3}, ConvertAndReverse.digitize(35231));
  }
}

Solution in Java

Option 1 (using Streams and StringBuilder):

import java.util.*;

public class ConvertAndReverse {
  public static int[] digitize(long n) {
    StringBuilder sb = new StringBuilder(Long.toString(n)).reverse();
    
    return Arrays.stream(sb.toString().split(""))
                  .mapToInt(Integer::parseInt)
                  .toArray();
  }
}

Option 2 (using StringBuilder and Streams):

public class ConvertAndReverse {
  public static int[] digitize(long n) {
        return new StringBuilder().append(n)
                                  .reverse()
                                  .chars()
                                  .map(Character::getNumericValue)
                                  .toArray();
  }
}

Option 3 (using Maths):

import java.lang.Math;
public class ConvertAndReverse {
  public static int[] digitize(long n) {
    String s = String.valueOf(n);
    int length = s.length();
    int[] array = new int[length];
    for ( int i = 0; i < length; i++){
      array[i] = (int) (s.charAt(length - i - 1)) - 48;
    }
    return array;
  }
}

More test coverage

import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;

public class DigitizeTests {
  @Test
  public void basicTests() {
    String msg = "Should work with some preset numbers";
    assertArrayEquals(msg, new int[] {1,3,2,5,3}, ConvertAndReverse.digitize(35231));
    assertArrayEquals(msg, new int[] {7,5,3,2,8,5,3,2}, ConvertAndReverse.digitize(23582357));
    assertArrayEquals(msg, new int[] {8,3,7,4,6,7,4,8,9}, ConvertAndReverse.digitize(984764738));
    assertArrayEquals(msg, new int[] {0,2,9,3,9,8,2,6,7,5,4}, ConvertAndReverse.digitize(45762893920L));
    assertArrayEquals(msg, new int[] {4,9,3,8,3,8,2,0,7,8,4,5}, ConvertAndReverse.digitize(548702838394L));
  }
  
  @Test
  public void randomTests() {
    int i, x;
    long y;
    System.out.println("Testing 37 random numbers...");
    for (i = x = 1; i <= 37; x = ++i) {
      y = (long) (10 + Math.ceil((9 * Math.pow(1.7, x) - 10) * Math.random()));
      assertArrayEquals("Should work with " + y, digitizeAns(y), ConvertAndReverse.digitize(y));
    }
  }
  
  private int[] digitizeAns(long n) {
    String numStr = Long.toString(n);
    int[] numArr = new int[numStr.length()];
    for (int i = numStr.length()-1; i >= 0; i--) {
      numArr[numStr.length() - 1 - i] = Integer.parseInt(numStr.substring(i, i+1));
    }
    return numArr;
  }
}