Skip to content

Commit 81889df

Browse files
committed
update base 26 qs
1 parent 27d58c6 commit 81889df

1 file changed

Lines changed: 11 additions & 26 deletions

File tree

‎src/com/interview/misc/ConvertNumberIntoBase26.java‎

Lines changed: 11 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,34 @@
11
package com.interview.misc;
22

33
/**
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/
66
*/
77
public class ConvertNumberIntoBase26 {
88

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) {
1610
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;
2215
}
2316
return buff.reverse().toString();
2417
}
2518

26-
public int base26ToNumber(String str){
19+
public int base26ToNumber(String str) {
2720
int result = 0;
2821
int pow = 1;
29-
for(int i = str.length() -1; i>=0; i--){
22+
for(int i = str.length() - 1; i>=0; i--) {
3023
char s = str.charAt(i);
3124
s = (char)(s - 'A'+1);
3225
result += s*pow;
3326
pow *= 26;
3427
}
3528
return result;
3629
}
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[]) {
4732
ConvertNumberIntoBase26 cni = new ConvertNumberIntoBase26();
4833
System.out.println(cni.numberToBase26(704));
4934
System.out.println(cni.base26ToNumber("AAB"));

0 commit comments

Comments
 (0)