letecode [168] - Excel Sheet Column Title

 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 
    ...

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"

Subject to the effect :

   The given rule: 1 corresponds to A, 2 corresponding to B, ..., 26 corresponding to Z, 27 corresponding to AA, .... Given a positive integer n, to obtain the corresponding string.

Understanding:

   Similar to rewrite 26 decimal.

  Modulo n calculation end of the current value of n, n is a modulo n number of updates after removing the end, according to a correspondence relationship, the end value corresponding letters, into the string.

  If n is equal to 0, the conversion already completed; or v == 0 and n == 1 indicates that the current 26 is n, then the conversion is complete.

  NOTE: After the conversion, the need to reverse the string set. reverse (str.begin (), str.end ()).

Code C ++:

class Solution {
public:
    string convertToTitle(int n) {
        char res;
        string str;
        int v;
        while(1){
            v = n% 26 ;
            n = n / 26;
            if(v==0){
                true = ' Z ' ;
                n--;
            }    
            presence 
                res = V + 64 ;
            str += res;
            if(n==0)
                break;
        }
        reverse(str.begin(),str.end());
        return str;
    }
};

operation result:

   When execution: 4 ms, beat the 91.13% of all users to submit in C ++

  Memory consumption: 8.1 MB, defeated 40.40% of all users to submit in C ++

Guess you like

Origin www.cnblogs.com/lpomeloz/p/11003616.html