168. Excel Sheet Column Title

来源:互联网 发布:域名投资人 编辑:程序博客网 时间:2024/05/17 20:25

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 
Solution 1 0ms 7.23%

public class Solution {    public String convertToTitle(int n) {        if (n <= 0) {            return "";        }        StringBuilder res = new StringBuilder();        while (n > 0) {            if (n % 26 == 0) {                res.append('Z');                n = n / 26 - 1;            } else {                char crt = (char)('A' + n % 26 - 1);                res.append(crt);                n = n / 26;                         }        }        return res.reverse().toString();    }}

Solution 2 

0ms 7.23

public class Solution {    public String convertToTitle(int n) {        if (n == 0) {            return "";        }        return convertToTitle((n - 1) / 26) + (char)((n - 1) % 26 + 'A');    }}


0 0