The challenge

We need a function that can transform a number into a string.

What ways of achieving this do you know?

Examples:

1
2
Solution.numberToString(123); // returns "123";   
Solution.numberToString(999); // returns "999";

The solution in Java code

The easiest way to do this is to use the String.valueOf method to take an integer and return a string:

1
2
3
4
5
class Solution {
  public static String numberToString(int num) {
    return String.valueOf(num);
  }
}

This can also be done the other way around, using the Integer.toString method:

1
2
3
4
5
class Solution {
  public static String numberToString(int num) {
    return Integer.toString(num);
  }
}

Test cases to validate our Java code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class NumberStringExampleTests {
  @Test
  public void tests() {
    assertEquals("67", Solution.numberToString(67));
    assertEquals("123", Solution.numberToString(123));
    assertEquals("999", Solution.numberToString(999));
  }
}