PhoneNumber

Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.

String.format()

First try, Prefixed numbers is fixed

we can simply cut out

public static String createPhoneNumber(int[] numbers) {  
    // Your code here!  
    String country = numbers[0] + "" + numbers[1] + "" + numbers[2];  
    String area = numbers[3] + "" + numbers[4] + "" + numbers[5];  
    String pop = "";  
    for (int i = 6; i <= numbers.length - 1; i++) {  
        pop = pop + numbers[i] + "";  
    }    return "(" + country + ")" + " " + area + "-" + pop;  
}

76ms

But There has an more elegant way to do so.

Use String.format()

public static String createPhoneNumber(int[] numbers){  
    return String.format("(%d%d%d) %d%d%d-%d%d%d%d",numbers[0],numbers[1],numbers[2],numbers[3],numbers[4],numbers[5],numbers[6],numbers[7],numbers[8],numbers[9] );  
}

But this method have to compile formatter, which caused extra time.

Over all, we can use StringBuffer to put Strings together.

public static String createPhoneNumber(int[] numbers) {  
    // Your code here!  
   return new StringBuilder()  
           .append("(")  
           .append(numbers[0])  
           .append(numbers[1])  
           .append(numbers[2])  
           .append(") ")  
           .append(numbers[3])  
           .append(numbers[4])  
           .append(numbers[5])  
           .append("-")  
           .append(numbers[6])  
           .append(numbers[7])  
           .append(numbers[8])  
           .append(numbers[9])  
           .toString();  
}

76ms

Actually, It did not saving time, but use less space.

So recommend third method.

Last modified April 7, 2025: update codewar (7e82e67)