LeetCode 168 Excel Sheet Column Title

xiaoxiao2021-02-27  458

168. Excel Sheet Column Title

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

难度EASY。相当于是26进制转换,稍微做点处理。

class Solution { public: string convertToTitle(int n) { string s = ""; while(n) { int x = --n % 26; s += 'A' + x; n /= 26; } reverse(s.begin(),s.end()); return s; } };

还有一种更简单的写法,避免用Reverse,直接利用递归栈的思想。 如下:

class Solution { public: string convertToTitle(int n) { return n == 0 ? "" : convertToTitle(n / 26) + (char) (--n % 26 + 'A'); } };
转载请注明原文地址: https://www.6miu.com/read-3047.html

最新回复(0)