Skip to content

Instantly share code, notes, and snippets.

@jatinsharrma
Created May 29, 2021 15:49
Show Gist options
  • Save jatinsharrma/e7697ad606b3d4674b41ab823f7ed08b to your computer and use it in GitHub Desktop.
Save jatinsharrma/e7697ad606b3d4674b41ab823f7ed08b to your computer and use it in GitHub Desktop.
Excel Column Address problem | CPP | C++
#include <iostream>
#include <math.h>
#define TOTAL 26
/*
Logic
Lets take the example of "A B C"
Let answer = 0
Our String size is 3.
To reach string size 3 we must have used all combinations possible of length 2.
Which means 26*26 combinations we have seen to have string length of 3.
Our CHARACTER 1 is A, this means we have seen 26*26 combination just once.
So we update our answer += 1*26*26 = 676;
Now we jump to second CHARACTER B. Same process, we reached to length 2 after we have seen all combinations of length 1 i.e 26 combinations
Our CHARACTER is B which means we have seen 26 combination 2 times.
So answer += 26*2 = 728
Now we jump to last CHARACTER C,nothing after that so we just add it
So answer += 3 = 731;
In short
26^ 2 * A + 26^1 * B + 26^0 * C = 731
*/
int address(std::string cell)
{
int ads = 0;
for(int i=cell.size(), j=0; i>0 ; i--,j++){
int a = cell[j] - 64;
ads += (pow(TOTAL,i-1) * a);
}
return ads;
}
/*
logic
This is just optimised version of above.
if you look closely .
26^ 2 * A + 26^1 * B + 26^0 * C = 731
It look same as we convert Base(x) to Base(10)
example 101 is 5 in Base 2
1*2^2 + 0*2^1 + 1*2^0 = 5
Below code is just converting Base(26) to Base(10)
*/
int alternate(std::string cell)
{
int ads = cell[0] -64;
for(int i=0; i<cell.size()-1; i++){
int n = cell[i+1] -64;
ads = TOTAL*ads + n;
}
return ads;
}
int main()
{
std::string cell;
std::cin >> cell;
std::cout << address(cell) << '\n';
std::cout << alternate(cell) << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment