C++ Exercises: Get the Excel column title that corresponds to a given column number
C++ Math: Exercise-7 with Solution
Write a C++ program to get the Excel column title that corresponds to a given column number (integer value).
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
Sample Solution:
C++ Code :
#include <iostream>
using namespace std;
string convert_num_to_Excel_Title(int num) {
if (num == 0) {
return "";
}
return convert_num_to_Excel_Title((num - 1) / 26) + static_cast<char>((num - 1) % 26 + 'A');
}
int main(void)
{
int n = 2;
cout << "\nColumn Number n = " << n << " Excel column title = " << convert_num_to_Excel_Title(n) << endl;
n = 29;
cout << "\nColumn Number n = " << n << " Excel column title = " << convert_num_to_Excel_Title(n) << endl;
n = 153;
cout << "\nColumn Number n = " << n << " Excel column title = " << convert_num_to_Excel_Title(n) << endl;
return 0;
}
Sample Output:
Column Number n = 2 Excel column title = B Column Number n = 29 Excel column title = AC Column Number n = 153 Excel column title = EW
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to get the fraction part from two given integers representing the numerator and denominator in string format.
Next: Write a C++ program to get the column number (integer value) that corresponds to a column title as appear in an Excel sheet.
What is the difficulty level of this exercise?