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 -> ABUnderstand the problem:
A classic 10-based math to 26-based math. Remember for a 10-based integer, e.g. 123, how can we extract each digit? The idea is from the least significant digit and use %10 and /10 respectively. e.g.
123 % 10 = 3, 123 / 10 = 12
12 % 10 = 2, 12 / 10 = 1
1 % 10 = 1, 1 / 10 - 0.
Therefore, for this question, we only need to replace 10 to 26. Note that for this question, the map is from 1 to 26. Therefore, we need to minus 1 for each number before the computation.
Code (Java):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public class Solution { public String convertToTitle( int n) { if (n <= 0 ) { return "" ; } StringBuffer sb = new StringBuffer(); convertToTitleHelper(n, sb); sb.reverse(); return sb.toString(); } private void convertToTitleHelper( int n, StringBuffer sb) { if (n <= 0 ) { return ; } n--; int val = n % 26 ; val = val < 0 ? val + 26 : val; char title = ( char ) (val + 'A' ); sb.append(title); convertToTitleHelper(n / 26 , sb); } } |
Update on 10/14/15:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class Solution { public String convertToTitle( int n) { if (n <= 0 ) { return "" ; } StringBuffer sb = new StringBuffer(); while (n > 0 ) { n--; int val = n % 26 ; char title = ( char ) (val + 'A' ); sb.insert( 0 , title); n /= 26 ; } return sb.toString(); } } |
No comments:
Post a Comment