每天一道LeetCode-----将数字用字母表示(本质是26进制转换)
生活随笔
收集整理的這篇文章主要介紹了
每天一道LeetCode-----将数字用字母表示(本质是26进制转换)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Excel Sheet Column Title
原題鏈接Excel Sheet Column Title
講數(shù)字轉(zhuǎn)為字母’A’到’Z’表示,對(duì)應(yīng)關(guān)系如圖
思路:
本質(zhì)上是將10盡職轉(zhuǎn)為26進(jìn)制,不同的是模的結(jié)果從[0:25]變?yōu)?span id="ozvdkddzhkzd" class="MathJax_Preview">[1:26]
假設(shè)1<=n%26<=26,那么0<=(n?1)%26<=25,所以可以每次取模時(shí)先減一
代碼如下
class Solution { public:string convertToTitle(int n) {string res("");do{res.append(1, 'A' + (n - 1) % 26);/* n - 1的目的是解決模結(jié)果為0的情況 */n = (n - 1) / 26;}while(n);std::reverse(res.begin(), res.end());return res;} };Excel Sheet Column Number
原題鏈接Excel Sheet Column Number
上一題的逆序,直接轉(zhuǎn)成26進(jìn)制即可
代碼如下
class Solution { public:int titleToNumber(string s) {return std::accumulate(s.begin(), s.end(), 0, [](auto n, auto value) { return n * 26 + (value - 'A' + 1); }); } };總結(jié)
以上是生活随笔為你收集整理的每天一道LeetCode-----将数字用字母表示(本质是26进制转换)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 每天一道LeetCode-----比较两
- 下一篇: 每天一道LeetCode-----摩尔投