Excel Column Letter Referencing
I'm trying to fix a method I made to reference Excel Column Letters based on the given number >1 where 1 = A.
Here is the method I have so far:
Code java:
public String getLetter(int n)
{
String[] letters = new String[] {"","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
String ans = "";
while(n>0)
{
ans = letters[n%27]+ans;
n = n/27;
System.out.println(n);
}
return ans;
}
Currently, this works great for numbers 1 - 26, but starting at 27 it craps out on me.
For 27, it returns A, where it should return AA. For 28, it returns AA, where it should return AB. And it continues offset like that.
There is definately something I'm missing here, can someone help me out?
Re: Excel Column Letter Referencing
Any reason why you have your array starting at 1 (eg letters[0] = "")? This is going to effect how your higher indexes are evaluated. I'd suggest removing the empty string and going from there (you'll have to change your while loop a bit to take into account the new indexes).
Re: Excel Column Letter Referencing
2 reasons.
1) My values received start at 1, so it only seemed to make sense to also start at 1.
2) I couldnt figure out how to change the loop to tell it to stop since I'm using Integer Division and I would need to get a 0 value.
Re: Excel Column Letter Referencing
Quote:
Originally Posted by
aussiemcgr
2 reasons.
1) My values received start at 1, so it only seemed to make sense to also start at 1.
2) I couldnt figure out how to change the loop to tell it to stop since I'm using Integer Division and I would need to get a 0 value.
I just mention the zero index because things can get quite messy with higher values. Easier for me to write the code than explain a fix, so have a look at the following...if the parameter you have is 1 based and not zero based, just send the function n-1.
Code java:
public String getLetter(int n)
{
String[] letters = new String[] {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
String ans = "";
while(n>-1)
{
ans = letters[n%26]+ans;
n = n/26 - 1;
}
return ans;
}