[LeetCode] 168. Excel Sheet Column Title, leetcode168.excel
[Question]
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB
[Analysis]
Becauseany_pos_int mod 26
Shocould return a number in the interval[0, 25]
, But what we want is a number in the interval[1, 26]
. Thus we have to shift the digit leftward1
Which means--n
.
[Code]
/********************************** Date: * Author: SJF0115 * Subject: 168. excel Sheet Column Title * URL: https://oj.leetcode.com/problems/excel-sheet-column-title/* result: AC * Source: LeetCode * blog: * *********************************/# include <iostream> # include <vector> # include <string> using namespace std; class Solution {public: string convertToTitle (int n) {if (n <= 0) {return "" ;}// if vector <int> vec; -- n; // except 26, the remainder is sorted in descending order while (n> = 0) {vec. push_back (n % 26); n/= 26; -- n;} // convert string result; int len = vec. size (); for (int I = 0; I <len; ++ I) {result. insert (result. begin (), vec [I] + 'A');} // for return result ;}}; int main () {Solution solution; for (int I = 500; I <800; ++ I) {string result = solution. convertToTitle (I); // output cout <result <"" ;}cout <endl; return 0 ;}
Code 2]
Class Solution {public: string convertToTitle (int n) {if (n <= 0) {return ";} // if string result; // except 26, the remainder is sorted in reverse order while (n> 0) {n --; result. insert (result. begin (), static_cast <char> (n % 26 + 'A'); n/= 26 ;}// return result ;}};