leetcode:Excel Sheet Column Title

本文探讨了将十进制数转换为Excel列名的高效算法,包括节省空间的方法、精炼代码实现及优化建议。文章还对比了不同解决方案的优劣,旨在提供一种更高效、更简洁的转换方法。

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

题目

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 

我的解法

这个其实就是一个进制的转换,相当于将十进制转换为26进制,可以参考
Leetcode:Number of 1 Bits

我的代码:

public class Solution {
    public String convertToTitle(int n) {
        char[] A = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        String str = "";
        while (n > 26) {
            int reminder = n % 26;
            if (reminder == 0) {
                str = A[25] + str;
                 n--;
            }
            else {
                str = A[reminder - 1] + str;
            }
            n /= 26;
        }
        if (n == 26)
            str = A[25] + str;
        else
            str = A[n - 1] + str;
        return str;
    }
}

缺点
保存26个单词表,浪费空间,后边因为这个数组下标对应问题,折腾好久。

参考答案:

方法一:

及其精炼!!

public class Solution {
    public String convertToTitle(int n) {
        return n == 0 ? "" : convertToTitle(--n / 26) + (char)('A' + (n % 26));
    }
}
方法二:
public class Solution {
    public String convertToTitle(int n) {
        StringBuilder result = new StringBuilder();

        while(n>0){
            n--;
            result.insert(0, (char)('A' + n % 26));
            n /= 26;
        }

        return result.toString();
    }
}

当然,上述代码中,StringBuilder可换成String,改为:

String column = "";
column = (char)('A' + n % 26) + column;

但是,StringBuilder效率比String要高,具体参考leetcode上的解释:

using simple String basically copies to a new variable, then add the new character to it. so, every time you add a character into a string, it copies the entire string, then adds the new character.【就是说,每次对String执行“+”操作,都会重新创建一个string,显然浪费内存空间】
StringBuilder doesn’t copy that string into a new variable, so it is more memory-efficient

当然有网友提到,如果不采用“头插法”拼接字符串,可以采用多次反转的办法:

1.Reverse each string you want to insert.
2.Append each string to a StringBuilder.
3.Reverse the entire StringBuilder when you’re done.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值