168. Excel Sheet Column Title的C++解法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/musechipin/article/details/85259506

题目描述:https://leetcode.com/problems/excel-sheet-column-title/

本能的想到是一个10进制转26进制,但是怎么做都做不对。其实是因为下标是从1开始而不是0,因此处理时要-1。

class Solution {
public:
    string convertToTitle(int n) {
        string res="";
        do
        {
            res=(char)((n-1)%26+'A')+res;//加在前面
            n=(n-1)/26;
            
        }while(n>0);
        return res;
    }
};

或者使用递归算法:
 

class Solution {
public:
    string convertToTitle(int n) {
        if (n == 0) {
            return "";
        }
        return convertToTitle((n - 1) / 26) + (char)((n - 1) % 26 + 'A');
    }
};

猜你喜欢

转载自blog.csdn.net/musechipin/article/details/85259506
今日推荐