【Lintcode】1730. Spreadsheet Notation Conversion

题目地址:

https://www.lintcode.com/problem/1730/

电子表格的行数有个唯一的字母表示,例如, 1 → A , 2 → B , . . . , 26 → Z , 27 → A A , 702 → Z Z 1\to A,2\to B,...,26\to Z, 27\to AA, 702\to ZZ 1A,2B,...,26Z,27AA,702ZZ,如果行数大于 702 702 702,那么其编号会回到 A A A继续向后走,但是最终的编号在首位应该加上其循环的数目,即 1 ∼ 702 1\sim 702 1702的编号对应的循环数是 1 1 1 703 ∼ 1404 703\sim 1404 7031404的循环数是 2 2 2,等等。例如, 3 3 3对应的字母表示是 1 C 1C 1C,而 28 28 28对应的是 1 A B 1AB 1AB。给定一个行数 n n n,求其表示。

我们先将 n n n自减 1 1 1,可以看到其循环数就是 ⌊ n 702 ⌋ + 1 \lfloor\frac{n}{702}\rfloor+1 702n+1,然后其最后一个字母是每 26 26 26一个循环,是 n % 26 + ′ A ′ n\% 26+'A' n%26+A,而其首字母是 ⌊ n 26 ⌋ − 1 + ′ A ′ \lfloor\frac{n}{26}\rfloor-1+'A' 26n1+A。代码如下:

public class Solution {
    /**
     * @param index: the index to be converted
     * @return: return the string after convert.
     */
    public String convert(long index) {
        // write your code here
        index--;
        StringBuilder sb = new StringBuilder(String.valueOf((index / 702) + 1));
        index %= 702;
        
        if (index / 26 > 0) {
            sb.append((char) ((index / 26) - 1 + 'A'));
        }
        
        sb.append((char) (index % 26 + 'A'));
        
        return sb.toString();
    }
}

时空复杂度 O ( 1 ) O(1) O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值