LeetCode 168 Excel table column name (Java implementation)

Title description:

Title description

It is worth noting that the decimal system is 0 1 2 3 4 5 6 7 8 9; the binary system is 0 1.
In the question, 1 corresponds to A, 2 corresponds to B...26 corresponds to Z, starting from 1, not 0. Therefore, a minus one operation is required.
Mainly 1-26 is a single letter, 27-+~ is multiple letters (at least two, and starting from AA), code two I took this as a breakthrough point, I tried it twice before writing it correctly, the first time ZY is not handled properly, and AnullY is output, which is a carry problem.
Code two is made with HashMap, code one is ASCII code.
PS: I feel that HashMap understands the meaning of the question better

Code one:

class Solution {
    
    
    public String convertToTitle(int n) {
    
    
        StringBuilder sb = new StringBuilder();
        while(n>0){
    
    
            n--;
            sb.append((char) ('A' + n % 26));
            n = n / 26;
        }
        return sb.reverse().toString();
    }
}

result:

result



Code two (HashMap):

class Solution {
    
    
    public String convertToTitle(int n) {
    
    
        HashMap<Integer,Character> map = new HashMap<Integer,Character>();
        int c = 0;
        for(char i = 'A';i <= 'Z';i++){
    
    
            map.put(c++,i);
        }
        StringBuilder sb = new StringBuilder();
        if(n <= 26){
    
    
            sb.append(map.get(n-1));
        }else{
    
    
            while(n>0){
    
    
                n--;
                sb.append(map.get(n % 26));
                n = n / 26;
            }
        }
        return sb.reverse().toString();
    }
}

result:
result

Guess you like

Origin blog.csdn.net/weixin_43752257/article/details/110679292