Skip to content

Latest commit

 

History

History
187 lines (145 loc) · 3.69 KB

File metadata and controls

187 lines (145 loc) · 3.69 KB
comments difficulty edit_url tags
true
简单
数学
字符串

English Version

题目描述

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

例如:

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

 

示例 1:

输入:columnNumber = 1
输出:"A"

示例 2:

输入:columnNumber = 28
输出:"AB"

示例 3:

输入:columnNumber = 701
输出:"ZY"

示例 4:

输入:columnNumber = 2147483647
输出:"FXSHRXW"

 

提示:

  • 1 <= columnNumber <= 231 - 1

解法

方法一

Python3

class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
        res = []
        while columnNumber:
            columnNumber -= 1
            res.append(chr(ord('A') + columnNumber % 26))
            columnNumber //= 26
        return ''.join(res[::-1])

Java

class Solution {
    public String convertToTitle(int columnNumber) {
        StringBuilder res = new StringBuilder();
        while (columnNumber != 0) {
            --columnNumber;
            res.append((char) ('A' + columnNumber % 26));
            columnNumber /= 26;
        }
        return res.reverse().toString();
    }
}

Go

func convertToTitle(columnNumber int) string {
	res := []rune{}
	for columnNumber != 0 {
		columnNumber -= 1
		res = append([]rune{rune(columnNumber%26 + int('A'))}, res...)
		columnNumber /= 26
	}
	return string(res)
}

TypeScript

function convertToTitle(columnNumber: number): string {
    let res: string[] = [];
    while (columnNumber > 0) {
        --columnNumber;
        let num: number = columnNumber % 26;
        res.unshift(String.fromCharCode(num + 65));
        columnNumber = Math.floor(columnNumber / 26);
    }
    return res.join('');
}

Rust

impl Solution {
    #[allow(dead_code)]
    pub fn convert_to_title(column_number: i32) -> String {
        let mut ret = String::from("");
        let mut column_number = column_number;

        while column_number > 0 {
            if column_number <= 26 {
                ret.push((('A' as u8) + (column_number as u8) - 1) as char);
                break;
            } else {
                let mut left = column_number % 26;
                left = if left == 0 { 26 } else { left };
                ret.push((('A' as u8) + (left as u8) - 1) as char);
                column_number = (column_number - 1) / 26;
            }
        }

        ret.chars().rev().collect()
    }
}

C#

public class Solution {
    public string ConvertToTitle(int columnNumber) {
        StringBuilder res = new StringBuilder();
        while (columnNumber != 0) {
            --columnNumber;
            res.Append((char) ('A' + columnNumber % 26));
            columnNumber /= 26;
        }
        return new string(res.ToString().Reverse().ToArray());
    }
}