leetcode 168: Excel Sheet Column Title

来源:互联网 发布:javascript generator 编辑:程序博客网 时间:2024/05/05 21:39

Transform the decimal number into a 26-scale number. Take care of the case that the number after mod is 0. Also, when the number is very big, long long will be needed.

class Solution {public:    string convertToTitle(int n) {        string res;        long long num=n;        long long divider=1;        while(num)        {            long long a=(num%(divider*26))/divider;            if(!a)                a=26;            res+=a+'A'-1;            num-=a*divider;            divider*=26;        }        reverse(res.begin(),res.end());        return res;    }};

Updated version:

class Solution {public:    string convertToTitle(int n) {        string res;        while(n)        {            n--;            res+=n%26+'A';            n=n/26;        }        reverse(res.begin(),res.end());        return res;    }};


0 0
原创粉丝点击