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
A:
public class Solution {
public String convertToTitle(int n) {
String result = "";
while(n>0){
int value = n % 26;
if(value ==0){
value = 26;
}
result = (char)('A'+value-1)+result;
n = (n-value) / 26;
}
return result;
}
}
Mistakes:
1: 应该是 (n+1)%26. 而非 n%26+1 自己想想为什么
2: n%26 + 'A' 的结果是个int
‘A’ + n%26 的结果是????? 也TMD是int
3: 简单的拍脑门是不行的。
肯定会出错, 例如 input == 26的时候,
不能简单的做除法。而应该是先减法,减去刚刚用过的部分,(为什么?因为我们前面不是简单的 求模运算,还对模==0的情况,做了特别处理 !!!!!!!!!
public class Solution {
public String convertToTitle(int n) {
if(n<=26){
return ""+(char)('A'+n-1);
}else{
return convertToTitle( (n-1)/26 ) + convertToTitle( (n-1) %26 +1 );
}
}
}
No comments:
Post a Comment