|
1 | 1 | package com.interview.misc; |
2 | 2 |
|
3 | 3 | /** |
4 | | - * http://www.careercup.com/question?id=6139456847347712 |
5 | | - * Test case : 0 or negative number |
| 4 | + * Given a positive integer, return its corresponding column title as appear in an Excel sheet. |
| 5 | + * https://leetcode.com/problems/excel-sheet-column-title/ |
6 | 6 | */ |
7 | 7 | public class ConvertNumberIntoBase26 { |
8 | 8 |
|
9 | | - /** |
10 | | - * Here 1..26 is A...Z |
11 | | - * 27...52 is AA...AZ. So we first try to divide num by 26 then find ceiling...so 27...52 returns 2. Then we subtract 1 from the number |
12 | | - * @param num |
13 | | - * @return |
14 | | - */ |
15 | | - public String numberToBase26(int num){ |
| 9 | + public String numberToBase26(int n) { |
16 | 10 | StringBuffer buff = new StringBuffer(); |
17 | | - while(num > 0){ |
18 | | - char r = convert(num % 26); |
19 | | - buff.append(r); |
20 | | - num = (int)(Math.ceil(num*1.0/26)); |
21 | | - num--; |
| 11 | + while (n > 0) { |
| 12 | + n--; |
| 13 | + buff.append((char)(n % 26 + 'A')); |
| 14 | + n = n / 26; |
22 | 15 | } |
23 | 16 | return buff.reverse().toString(); |
24 | 17 | } |
25 | 18 |
|
26 | | - public int base26ToNumber(String str){ |
| 19 | + public int base26ToNumber(String str) { |
27 | 20 | int result = 0; |
28 | 21 | int pow = 1; |
29 | | - for(int i = str.length() -1; i>=0; i--){ |
| 22 | + for(int i = str.length() - 1; i>=0; i--) { |
30 | 23 | char s = str.charAt(i); |
31 | 24 | s = (char)(s - 'A'+1); |
32 | 25 | result += s*pow; |
33 | 26 | pow *= 26; |
34 | 27 | } |
35 | 28 | return result; |
36 | 29 | } |
37 | | - |
38 | | - private char convert(int r){ |
39 | | - if(r == 0){ |
40 | | - return 'Z'; |
41 | | - }else{ |
42 | | - return (char)(r + 'A'-1); |
43 | | - } |
44 | | - } |
45 | | - |
46 | | - public static void main(String args[]){ |
| 30 | + |
| 31 | + public static void main(String args[]) { |
47 | 32 | ConvertNumberIntoBase26 cni = new ConvertNumberIntoBase26(); |
48 | 33 | System.out.println(cni.numberToBase26(704)); |
49 | 34 | System.out.println(cni.base26ToNumber("AAB")); |
|
0 commit comments