C#LeetCode刷题之#168-Excel表列名称(Excel Sheet Column Title)

本文介绍了一种将正整数转换为Excel表格中相应列名的算法,提供了三种不同的实现方式,并展示了各自的输出结果。通过递归和迭代的方法,算法能够高效地处理从1到任意大数的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

 

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3850 访问。

给定一个正整数,返回它在 Excel 表中相对应的列名称。

例如,

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
    ...

输入: 1

输出: "A"

输入: 28

输出: "AB"

输入: 701

输出: "ZY"


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

Input: 1

Output: "A"

Input: 28

Output: "AB"

Input: 701

Output: "ZY"


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3850 访问。

public class Program {

    public static void Main(string[] args) {
        var n = 701;
        var res = ConvertToTitle(n);
        Console.WriteLine(res);

        n = 678;
        res = ConvertToTitle2(n);
        Console.WriteLine(res);

        n = 12345;
        res = ConvertToTitle3(n);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static string ConvertToTitle(int n) {
        if(n <= 26) return ((char)(n + 'A' - 1)).ToString();
        if(n % 26 == 0) {
            return ConvertToTitle(n / 26 - 1) + 'Z';
        } else {
            return ConvertToTitle(n / 26) + ConvertToTitle(n % 26);
        }
    }

    private static string ConvertToTitle2(int n) {
        if(n <= 0) return "";
        return ConvertToTitle((n - 1) / 26) + (char)((n - 1) % 26 + 'A');
    }

    private static string ConvertToTitle3(int n) {
        var res = string.Empty;
        while(n > 0) {
            var s = (char)((n - 1) % 26 + 'A');
            res = s + res;
            n = (n - 1) / 26;
        }
        return res;
    }

}

以上给出3种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3850 访问。

ZY
ZB
RFU

分析:

显而易见,以上3种算法的时间复杂度均为: O(log_2_6n) 。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值