Problem
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
Java Solution
This problem is the reverse version of Excel Sheet Column Number.
The key is n--
. The minimum in 26-bit number is mapped to 1, not 0.
public String convertToTitle(int n) { if(n <= 0){ throw new IllegalArgumentException("Input is not valid!"); } StringBuilder sb = new StringBuilder(); while(n > 0){ n--; char ch = (char) (n % 26 + 'A'); n /= 26; sb.append(ch); } sb.reverse(); return sb.toString(); } |
static String ColToString(int col) {
int rem=col%26;
if(rem==0) {
col–;
rem=26;
}
String s=””;
if(col>26){
col/=26;
s=ColToString(col)+String.valueOf((char)(rem+64));
}
else {
s+=String.valueOf((char)(rem+64));
}
return s;
}
No need for anything. add char to string in java 8
Dont need the toString perhaps?
Good solution.Only just correct
s=String.valueOf((char)(n%26+’A’))+s;
You use a string builder because string concantenation operates in O(N^2) time
Noob
There is no need to use a StringBuilder.
string s = "";
while(n>0)
{
n--;
s = ((char)(n%26 +'A')).ToString() + s;
n/=26;
}
return s;
Leetcode accepted this.
Thank you for the simple solution!