Could somebody please explain how this formula 'result = result * 26 + (s[i] - 'A


#1

Could somebody please explain how this formula ‘result = result * 26 + (s[i] - ‘A’ + 1);’ in solution is achieved. I understand that it works but I wonder how it is derived. I used general result += A[n-i-1]*power(base,i); and I would like to understand what’s the logic behind proposed solution. It saves up many lines of code. Thank you.


#2

Hi Alex, Note that the formula
result += A[n-i-1]*power(base,i)
works when the numbers are 0 based. That is the numbers in the number system look like the following : [0, 1, 2, 3, …, 10, 11, …]
Here the letters are 1 based.
So, A corresponds to 1 instead of 0.
B corresponds to 2 instead of 1, and so on.


#3

I still did not get it can you elaborate more on this why this actually works. @anshumansingh what you are trying to explain is why do we do s[i] - ‘A’ + 1 but bot why the result = result * 26 this statement works.
i tried something like this and i dont understand why this works and how?
int result = 0;
for (int i = 0; i < s.size(); i++) {
result = result * 2 + (s[i] - ‘0’);
//cout<<s[i]<<" "<<result<<endl;
}
return result;
There are two methods for conversion from any base to decimal one is the positional notation and other is a doubling method and here is a link which explains why the doubling method works