Can not understand this error! Output: "A" Expected: "A"


  • 0
    W

    The error is :

    Input:
    1
    Output:
    "A"
    Expected:
    "A"

    My code is :

    public String convertToTitle(int n) {
        char[] ch = new char[7];// pow(26,7) > Integer.MAX_VALUE
        int i = 6;
        while( n > 0 ){
            n--;// as A == 1 remove 1
            ch[i] = (char)('A' + n % 26); 
            n = n / 26;
            i--;
        }
        return new String(ch);
    }
    

    Could you please help me to find out what the problem is. Many thanks


  • 0
    W

    I replaced char[] to String and the new code has been accepted. Wish someone could tell me why. Many many thanks!

    public String convertToTitle(int n) {
        //char[] ch = new char[7];// pow(26,7) > Integer.MAX_VALUE
        //int i = 6;
        String s = "";
        while( n > 0 ){
            n--;// as A == 1 remove 1
            s = (char)('A' + n % 26) + s; 
            n = n / 26;
            //i--;
        }
        return s;
    }

  • 1

    If the result string is not of length = 7, your character array contains null characters as the prefix.

    For example, n = 1, ch = ['\u0000', '\u0000', '\u0000', '\u0000', '\u0000', '\u0000', 'A'], since you only set ch[6] in the for loop. (See what's the default value of char)

    When you convert it to a string, it will contain the null characters before 'A'.


  • 0
    S

    where do you get confused?


  • 0
    P

    1337c0d3r answered you: your original code created an array of 7 char, which by default is pre-filled with character ASCII 0. Then you filled the array with letters from right to left, but if the result was less than 7 characters long, the front of your array still contained several ASCII 0. Changing your code to prepend into a string fixed this issue.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.