Could you help me improve my code? Thanks!


  • 0
    M
     public static String convertToTitle(int n) {
            if(n<=0)
            return "";
            StringBuffer sb=new StringBuffer();
            String res="";
       
            while(n>26){
                int cur=n%26;
                if(cur==0){
                	sb.insert(0, 'Z');
                	n--;
                }else{
                	char b=(char)(cur+64);
      	            sb.insert(0,b);	
                }
              
                n=n/26;
                if(n<=26){
                char c=(char)(n+64);
                sb.insert(0,c);
                res=sb.toString();
                return res;
                }
            }
             char b=(char)(n+64);
            res=res+b;
            return res;
            
        }

  • 0
    Y
    public static String convertToTitle(int n) {
        StringBuffer sb=new StringBuffer();
        while(n!=0){
            int cur=n%26;
            if(cur==0){
                sb.insert(0, 'Z');
                n=n/26;
                n--;
            }else{
                char b=(char)(cur+64);
                sb.insert(0,b); 
                n=n/26;
            }
        }
        return sb.toString();
    }

  • 0
    Y

    n=a0+a126+a226^2+....+an26^n
    a0,a1,a2...an are between 1 and 26 inclusively.
    If a0=26, then n/26=1+a1+a2
    26+...+an*26^(n-1), so you need to decrease n by 1 after n/=26


  • 0
    S
    public String convertToTitle(int n) {
            if (n < 1 || n > 16384) return null; // excel 2007 row title from 'A' to 'XFD'
            String columnTitle = "";
            while (n > 26) {
                int mod = n % 26;
                if (mod == 0) {
                    mod = 26;
                    n = n - 26;
                }
                n = n / 26;
                columnTitle = (char) (mod + 64) + columnTitle;
            }
            return (char) (n + 64) + columnTitle;
        }
    
        public long getRowNum(String str) { // validate method
            long rowNum = 0L;
            int iLen = str.length();
            for (int i = 0; i < iLen; i++) {
                rowNum += (Integer.valueOf(str.charAt(i)) - 64) * (long) Math.pow(26, iLen - 1 - i);
            }
            return rowNum;
        }

  • 0
    D

    StringBuilder result = new StringBuilder();
    while(n > 0) {
    if(n % 26 == 0) {
    result.append('Z');
    } else {
    result.append((char) ('A' + n%26 - 1));
    }
    n = (n - 1) / 26;
    }
    return result.reverse().toString();


Log in to reply
 

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