Bootstrap

闯关leetcode——168. Excel Sheet Column Title

题目

地址

https://leetcode.com/problems/excel-sheet-column-title/description/

内容

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

For example:

A -> 1
B -> 2
C -> 3

Z -> 26
AA -> 27
AB -> 28

Example 1:

Input: columnNumber = 1
Output: “A”

Example 2:

Input: columnNumber = 28
Output: “AB”

Example 3:

Input: columnNumber = 701
Output: “ZY”

Constraints:

  • 1 <= columnNumber <= 231 - 1

解题

这题就是要将整型数字转换成EXCEL风格的26进制表达。除了二进制,所有进制问题都是取模再除法,从低向高位计算。但是这题有个小陷阱,就是它的数值关系中并不存在0。这样我们就需要做个转换,将数字值减少一,再去做取模或者除法。这样取模为0,就是A。27减去1得到26,取模为0,则低位为A。高位26/26等于1,1再减去1得到0,取模得到0,这样高位就为A。于是27表达为AA。

#include <string>
using namespace std;

class Solution {
public:
    string convertToTitle(int columnNumber) {
        string result;
        int base = 26;

        while (columnNumber > 0) {
            columnNumber--;
            result = char('A' + columnNumber % base) + result;
            columnNumber = columnNumber / base;
        }

        return result;
    }
};

在这里插入图片描述

代码地址

https://github.com/f304646673/leetcode/tree/main/168-Excel-Sheet-Column-Title/cplusplus

;