0 ms Java solution


  • 4
    P
    public String convertToTitle(int n) {
        StringBuilder sb = new StringBuilder();
        while (n > 0){
            int r = n % 26;
            n = n/26;
            if (r != 0){
                sb.append((char)(r - 1 + 'A'));
            } else {
                sb.append('Z');
                n--;
            }
            
        }
        return sb.reverse().toString();
    }

  • 0
    C

    Almost he same as mine. :)

    	private final int ZERO = 64;
    public String convertToTitle(int n) {
        if(n <= 0) return "";
        
        String result = "";
        while(n > 0){
        	int digit = n % 26;
        	n /= 26;
        	if(digit == 0){//if this is 0, because excel doesn't have 0, we need to compensate it to 26.
        		digit = 26;
        		n --;
        	}
        	result = (char)(digit + ZERO) + result;
        }
        return result;
    }

Log in to reply
 

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