Naim_Hasan's blog

By Naim_Hasan, history, 6 months ago, In English,

Update: Solved. Special thanks to mello

Hello,

I was solving this https://codeforces.com/contest/1/problem/B

I have write one function to convert an Alphabet number into decimal number.

For example BC turns into 55. Similarly RZ becomes 494.

Here is my implementation https://ideone.com/2J0hCq

But i am facing problem to do the reverse.

For 55, my code shows BC which is right but for 494 it shows S@ which is wrong.

Here is my implementation https://ideone.com/OuUJD3

I found that the problem is causing when input is a multiple of 26.

Help needed.

 
 
 
 
  • Vote: I like it
  • -14
  • Vote: I do not like it

»
6 months ago, # |
  Vote: I like it 0 Vote: I do not like it

If y == 0, that’s when you get the @ sign. Instead, if y == 0, put a Z there because A-Y is 1-25, so Z is the only one left to be 0. Then your code will look like this:

string F(int n){
	
	string Ans;
	
	while(n){
		
		int y = n%26;
		
		if (y == 0){
                  Ans += ‘Z’;

		}else{
                  Ans += (char)(y+'A'-1);
	
		}
				
		n /= 26;
	}
	
	reverse(Ans.begin(),Ans.end());
	
	return Ans;
}

This doesn’t work for multiples of 26 though. For 26 it outputs AZ and for 52 it outputs BZ. This is because the Z at the end counts as 1 extra 26. You see for AZ and BZ, they would be correct if they were Z and AZ. To correct this, after n /= 26, do n-- only if you just put a Z. Then, the code will look like this:

string F(int n){
	
	string Ans;
	
	while(n){
		
		int y = n%26;
		
		if (y == 0){
                  Ans += ‘Z’;
                  n /= 26;
                  n--;
	
		}else{
                  Ans += (char)(y+'A'-1);
                  n /= 26;
	
		}
				
		
	}
	
	reverse(Ans.begin(),Ans.end());
	
	return Ans;
}

»
6 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Naim_Hasan (previous revision, new revision, compare).

»
6 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Naim_Hasan (previous revision, new revision, compare).