168. Excel Sheet Column Title

題目:java

Given a positive integer, return its corresponding column title as appear in an Excel sheet.python

For example:app

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 

連接: http://leetcode.com/problems/excel-sheet-column-title/學習

題解:ui

轉換數字和excel column title。數學題,寫幾個例子找到規律就能夠了,好比53, 52, 26, 27等等。規律是,當n > 0時, 假如n % 26 == 0,則n爲26的倍數,要轉換爲'Z'插入隊首,以後n = n / 26 - 1, 假如n % 26 != 0, 則使用通常方法計算字符,int c = 'A' + n % 26 - 1, 以後 n /= 26。spa

Time Complexity - O(N), Space Complexity - O(1)。excel

public class Solution {
    public String convertToTitle(int n) {
        if(n <= 0)
            return "";
        StringBuilder result = new StringBuilder();
        
        while(n > 0) {
            if(n % 26 == 0) {           // n is multiple of 26,  example - 52 - 'AZ'
                result.insert(0, 'Z');
                n = n / 26 - 1;
            } else {
                int c = 'A' + n % 26 - 1;   // example - 27 - 'AA'
                result.insert(0, (char)c);
                n /= 26;
            }
        }
        
        return result.toString();
    }
}

 

二刷:code

二刷好好參考瞭解答。 使用了一個很巧妙的小技術,把n映射到0-25這26個數字裏,咱們能夠先n--, 而後再進行後面的轉換 -  n % 26 + 'A',  最後n /= 26.blog

這個小技巧和Permutation Sequence很像,要好好學習。ip

Java:

public class Solution {
    public String convertToTitle(int n) {
        if (n < 1) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        while (n > 0) {
            n--;
            sb.insert(0, (char)(n % 26 + 'A'));
            n /= 26;
        }
        return sb.toString();
    }
}

 

三刷:

二刷理解得不深入。

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

 

一刷的方法,用例子出發  - 'AZ' = 52,  - 'AA' = 27

public class Solution {
    public String convertToTitle(int n) {
        if (n <= 0) return "";
        StringBuilder sb = new StringBuilder();
        while (n > 0) {
            if (n % 26 == 0) {
                sb.insert(0, 'Z');          // 52 = "AZ"
                n = n / 26 - 1;
            } else {
                sb.insert(0, (char)(n % 26 - 1 + 'A'));  // 27 = "AA"
                n = n / 26;
            }
        }
        return sb.toString();
    }
}

 

 

Reference:

https://leetcode.com/discuss/19047/my-1-lines-code-in-java-c-and-python

https://leetcode.com/discuss/19044/share-simple-solution-just-little-trick-handle-corner-case

https://leetcode.com/discuss/34526/share-my-java-solusion

https://leetcode.com/discuss/25667/short-solution-without-using-string-buffer-string-builder

https://leetcode.com/discuss/19135/solution-with-explanation

https://leetcode.com/discuss/82531/my-easy-to-understand-java-solution

相關文章
相關標籤/搜索