【leetcode】168. Excel Sheet Column Title(Python & C++)

51 篇文章 1 订阅
50 篇文章 28 订阅

168. Excel Sheet Column Title

题目链接

168.1 题目描述:

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 

168.2 解题思路:

  1. 思路一:类似于十进制转二进制。只不过这里是26进制,但是又和标准的26进制不同,这里不存在0位,也就是只有1-26,即A-Z。初始化字符串s=”“。循环n大于0,首先n对26取余,d=n%26,n=n/26,如果d不为0的话,则直接将d+64转化为字符加在字符串s前面。如果d为0,则d=26,且n–。因为当n是26的倍数时,并没有进位,还是Z。最后返回s即可。例如,n=26,并不是A0,而是Z。

  2. 思路二:等同于思路一,写法优化。在进入循环n大于0时,首先就对n=n-1。处理n是26的倍数这种情况。

168.3 C++代码:

1、思路一代码(0ms):

class Solution131 {
public:
    string convertToTitle(int n) {
        string s = "";
        if (n < 1)
            return s;
        int i = 1;
        while (n > 0)
        {
            int d = n % 26;
            n = n / 26;
            if (d == 0)
            {
                d = 26;
                n--;
            }
            char c = d + 64;
            s = c + s;
        }
        return s;
    }
};

2、思路二代码(0ms)

class Solution131_1{
public:
    string convertToTitle(int n) {
        string s = "";
        if (n < 1)
            return s;
        int i = 1;
        while (n > 0)
        {
            n = n - 1;
            int d = n % 26;
            n = n / 26;
            char c = d + 65;
            s = c + s;
        }
        return s;
    }
};

168.4 Python代码:

1、思路一代码(28ms)

class Solution(object):
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        s=""
        if n<1:
            return s
        while n>0:
            d=n%26
            n=n/26
            if d==0:
                n-=1
                d=26
            s=chr(64+d)+s
        return s

2、思路二代码(38ms)

class Solution1(object):
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        s=""
        if n<1:
            return s
        while n>0:
            n=n-1
            d=n%26
            n=n/26
            s=chr(65+d)+s
        return s

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值