很简单的一道题,不过实际上是转换进制,从10进制转换成27进制(实际上这也不能算一种进制,因为不能表达0),我感觉有记录的意义。
168.
Excel Sheet Column Title
Total Accepted: 90306
Total Submissions: 365463
Difficulty: Easy
Contributors: Admin
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
一开始的思路就是一位一位数往上加,最后在算总账。
public class Solution {
public String convertToTitle(int n) {
String str="";
int singleDigit=0;
int tensDigit=0;
int hundredsDigit=0;
int thousandsDigit=0;
for(int i=0;i<n;i++){
singleDigit++;
if(singleDigit>=27){
singleDigit%=26;
tensDigit++;
}
if(tensDigit>=27){
tensDigit%=26;
hundredsDigit++;
}
if(hundredsDigit>=27){
hundredsDigit%=26;
thousandsDigit++;
}
}
str+=getLetterFromNumber(thousandsDigit);
str+=getLetterFromNumber(hundredsDigit);
str+=getLetterFromNumber(tensDigit);
str+=getLetterFromNumber(singleDigit);
return str;
}
private static String getLetterFromNumber(int num){
switch(num){
case 1:
return "A";
case 2:
return "B";
case 3:
return "C";
case 4:
return "D";
case 5:
return "E";
case 6:
return "F";
case 7:
return "G";
case 8:
return "H";
case 9:
return "I";
case 10:
return "J";
case 11:
return "K";
case 12:
return "L";
case 13:
return "M";
case 14:
return "N";
case 15:
return "O";
case 16:
return "P";
case 17:
return "Q";
case 18:
return "R";
case 19:
return "S";
case 20:
return "T";
case 21:
return "U";
case 22:
return "V";
case 23:
return "W";
case 24:
return "X";
case 25:
return "Y";
case 26:
return "Z";
default:
return "";
}
}
}
前面的case都没问题,所以正确性应该是ok的。
结果后面有个test case
Last executed input:
1000000001
TLE了,所以只能乖乖用算出来了。这道题估计本意就是这样,所以时间卡的紧。毕竟这是个o(N)的方法,不应该TLE的。
做出来了。不过这个有个坑,因为前面1是等于A的,但是后面进制转换以后A实际上是充当了0,所以当Z的时候虽然用十进制来看前一位进了1但是实际上并没有进1,所以前一位要减一。
public class Solution {
public String convertToTitle(int n) {
String str="";
int ans=n;
do{
if(ans>26){
if(ans%26==0){
str+=getLetterFromNumber(ans%26);
ans/=26;
ans--;
}else{
str+=getLetterFromNumber(ans%26);
ans/=26;
}
}else{
str+=getLetterFromNumber(ans);
break;
}
}while(ans>0);
return reverseString(str);
}
private static String reverseString(String str){
char[] arr=str.toCharArray();
String tmp="";
for(int i=arr.length-1;i>=0;i--){
tmp+=arr[i];
}
return tmp;
}
private static String getLetterFromNumber(int num){
switch(num){
case 1:
return "A";
case 2:
return "B";
case 3:
return "C";
case 4:
return "D";
case 5:
return "E";
case 6:
return "F";
case 7:
return "G";
case 8:
return "H";
case 9:
return "I";
case 10:
return "J";
case 11:
return "K";
case 12:
return "L";
case 13:
return "M";
case 14:
return "N";
case 15:
return "O";
case 16:
return "P";
case 17:
return "Q";
case 18:
return "R";
case 19:
return "S";
case 20:
return "T";
case 21:
return "U";
case 22:
return "V";
case 23:
return "W";
case 24:
return "X";
case 25:
return "Y";
case 26:
return "Z";
case 0:
return "Z";
default:
return "";
}
}
}