I was solving the leetcode problem called excel sheet column number using c++. Please see the link for the question -> Excel Sheet Column Number I came up with the following solution.
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
#define val(c) (static_cast<int>(c) - 64)
int titleToNumber(string columnTitle) {
int result = 0;
int i = 0;
int n = columnTitle.length() - 1;
while(n >=0){
cout<<"Current value = "<<val(columnTitle[i])*(pow(26,n))<<endl;
result = result + val(columnTitle[i])*(pow(26,n));
cout<<"Result = "<<result<<endl;
n--;
i++;
}
return result;
}
int main(){
string s = "AA";
cout<<titleToNumber(s)<<endl;
return 0;
}
However, I am experiencing some unexpected error. I have initialized the value of result to 0 and when the program outputs the value of Current value it outputs it correctly which is 26, but when it adds and assigns the value to the variable result, the value somehow becomes 25. I checked the type of the value returned from the expression val(columnTitle[i])*(pow(26,n)) and it is of type double. I suspect that this is happening due to the type conversion from double to integer. However, the value of the expression is a whole number and does not have any floating part so there is no question of truncation. Also why the output value is 1 less than the expected?
Typecasting the expression value to integer doesn't help.
Can anyone please explain what is happening here and what I need to keep in mind in future for such conversions. Thank you.
Please note that when I run my solution on online c++ compiler such ashttps://www.onlinegdb.com/online_c++_compiler, the output is correct, but it is not correct when I run on my system. I am having g++.exe (MinGW.org GCC-6.3.0-1) 6.3.0 and I am also adding a snap of the output that I get.