【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)

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/114219917