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:
相当于10进制转26进制。对应的时候注意26进制里最小的对应10进制里的1, 而不是0, 所以在while循环中要n--。
Run time complexity is O(n), constant space.
public class Solution {
public String convertToTitle(int n) {
if(n <= 0) {
throw new IllegalArgumentException("Input number is invalid!");
}
StringBuilder sb = new StringBuilder();
while(n > 0) {
n--; //1->A
char c = (char)(n % 26 + 'A');
sb.append(c);
n /= 26;
}
return sb.reverse().toString();
}
}
No comments:
Post a Comment