Excel Sheet Column Number Solutions in C++
Number 171
Difficulty Easy
Acceptance 56.0%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/excel-sheet-column-number/// Author : Hao Chen// Date : 2014-12-29#include <stdio.h>#include <stdlib.h>#include <iostream>#include <string>using namespace std;string base26_int2str(long long n) {string ret;while(n>0){char ch = 'A' + (n-1)%26;ret.insert(ret.begin(), ch );n -= (n-1)%26;n /= 26;}return ret;}long long base26_str2int(string& s){long long ret=0;for (int i=0; i<s.size(); i++){int n = s[i] - 'A' + 1;ret = ret*26 + n;}return ret;}string titleToNumber(int n) {return base26_str2int(n);}int main(int argc, char**argv){long long n = 27;if (argc>1){n = atoll(argv[1]);}string ns = base26_int2str(n);n = base26_str2int(ns);cout << n << " = " << ns << endl;ns = "ABCDEFG";if (argc>2){ns = argv[2];}cout << ns << " = " << base26_str2int(ns) << endl;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/excel-sheet-column-number/description//// Author : liuyubobobo/// Time : 2018-08-30#include <iostream>#include <cmath>using namespace std;/// 26-based number/// Time Complexity: O(len(s))/// Space Complexity: O(1)class Solution {public:int titleToNumber(string s) {int num = 0;for(char c: s)num = num * 26 + (c - 'A' + 1);return num;}};int main() {cout << Solution().titleToNumber("A") << endl; // 1cout << Solution().titleToNumber("AB") << endl; // 28cout << Solution().titleToNumber("ZY") << endl; // 701return 0;}