C++ Exercises: Get the column number that corresponds to a column title as appear in an Excel sheet
C++ Math: Exercise-8 with Solution
Write a C++ program to get the column number (integer value) that corresponds to a column title as appear in an Excel sheet.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Sample Solution:
C++ Code :
#include <iostream>
using namespace std;
int excel_title_to_Number(string s) {
int number = 0;
for (const auto& c : s) {
number *= 26;
number += c - 'A' + 1;
}
return number;
}
int main(void)
{
string col_title1 ="C";
cout << "\nExcel column title = " << col_title1 << ", Corresponding number = " << excel_title_to_Number(col_title1) << endl;
col_title1 ="AD";
cout << "\nExcel column title = " << col_title1 << ", Corresponding number = " << excel_title_to_Number(col_title1) << endl;
col_title1 ="WX";
cout << "\nExcel column title = " << col_title1 << ", Corresponding number = " << excel_title_to_Number(col_title1) << endl;
return 0;
}
Sample Output:
Excel column title = C, Corresponding number = 3 Excel column title = AD, Corresponding number = 30 Excel column title = WX, Corresponding number = 622
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to get the Excel column title that corresponds to a given column number (integer value).
Next: Write a C++ program to find the number of trailing zeroes in a given factorial.
What is the difficulty level of this exercise?