MockInterview:168 Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
    ...
Example 1:
Input: 1
Output: "A"
Example 2:
Input: 28
Output: "AB"
Example 3:
Input: 701
Output: "ZY"

Wrong code:
test case: 52
class Solution {
    public String convertToTitle(int n) {
        char[] map = {' ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        StringBuilder sb = new StringBuilder();
        while(n!=0){
            int last = n % 26;
            if(last == 0){
                last = 26;
                char lastC = map[last];
                sb.insert(0,lastC);
                break;
            }else{
                char lastC = map[last];
                sb.insert(0,lastC);
                n = n / 26;
            }
        }
        return sb.toString();
    }
}

Correct code:
10进制的%是从0开始,10进制的个数是从0,1,2,3,4,5,6,7,8,9。所以26进制的个数也应该从0,1,2,3,4.....,23,24,25.
把AZ转成数字为(0+1)*26+25+1=num.倒过来,所以每次循环个位数都需要-1.

class Solution {
    public String convertToTitle(int n) {
        char[] map = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        StringBuilder sb = new StringBuilder();
        while(n!=0){
            n = n - 1;//每次循环
            int last = n % 26;
            char lastC = map[last];
            sb.insert(0,lastC);
            n = n / 26;
        }
        return sb.toString();
    }
}




Comments

Popular posts from this blog

geeksforgeeks:findFind zeroes to be flipped so that number of consecutive 1’s is maximized

geeksforgeeks:Connect n ropes with minimum cost

94.Binary Tree Inorder Traversal