leetcode 168. Excel Sheet Column Title | 进制转化
来源:互联网 发布:海报拼图软件 潘哒 编辑:程序博客网 时间:2024/06/05 15:54
Description
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A2 -> B3 -> C...26 -> Z27 -> AA28 -> AB
My solution
实际上是转化为26进制, 故采用经典的除K取余法(参考手算二进制方法). 但由于26是Z而非A0,所以要进行特殊处理, 第一次代码如下, Z样例未能通过, 尝试修改一个地方即可.
注意A-Z中A不是0, 仍然是26进制(非27), 从A-Z看为是0-25, 只不过字母到数字的转化后需要给每一位+1, 逆向来看, 就是n到字母的转化, 先–n !!
class Solution {public: string convertToTitle(int n) { char yu; string res=""; while (n) { yu = char(n % 26 + 65); res = yu+res; n /= 26; } return res; }};
修改为:
class Solution {public: string convertToTitle(int n) { char yu; string res=""; while (n) { // 注意此处--n,意识到n需要-1,但是n-1一定不要放在n/=26后面,会影响while判断!! yu = char(--n % 26 + 65); res = yu+res; n /= 26; // 一定不要在这里n--! } return res; }};
leetcode 171是此题的逆向, 基本代码如下, 注意’A’==65, 而这里采用64(原因和上述–n一致)
// 我的一次AC代码class Solution {public: int titleToNumber(string s) { int c=0; for (int i = 0; i<s.size(); i++) { c*=26; c += s[i] - 64; } return c; }};
Discuss
从discuss学得关于Z的处理, 即–n, 另外可以参考递归实现方案(感觉不如while来的直接):
return n == 0 ? "" : convertToTitle(n / 26) + (char) (--n % 26 + 'A');
Reference
- leetcode 168
阅读全文
0 0
- leetcode 168. Excel Sheet Column Title | 进制转化
- 168.leetcode Excel Sheet Column Title(easy)[进制转换]
- [LeetCode]168.Excel Sheet Column Title
- 168. Excel Sheet Column Title Leetcode Python
- LeetCode 168. Excel Sheet Column Title
- 【LeetCode】168.Excel Sheet Column Title
- [leetcode] 168.Excel Sheet Column Title
- [LeetCode]168. Excel Sheet Column Title
- 168. Excel Sheet Column Title LeetCode
- leetcode 168. Excel Sheet Column Title
- Leetcode: 168. Excel Sheet Column Title(JAVA)
- LeetCode *** 168. Excel Sheet Column Title
- leetcode-168. Excel Sheet Column Title
- [leetcode] 168. Excel Sheet Column Title
- leetcode-java-168. Excel Sheet Column Title
- LeetCode-168.Excel Sheet Column Title
- LeetCode 168. Excel Sheet Column Title
- [Leetcode]168. Excel Sheet Column Title
- 从门外汉的角度理解步步紧逼卷积神经网络
- Session
- TortoiseGit GitLab使用教程
- vue 端口号更改
- 计算机概述
- leetcode 168. Excel Sheet Column Title | 进制转化
- 关于Serializable的serialVersionUID
- js 树形结构数据 处理
- HDU 3466 Proud Merchants 贪心+dp
- Shiro中的加密和验证策略
- HDUoj 5113 Black And White (dfs&剪枝
- 欢迎使用CSDN-markdown编辑器
- vs2013 mfc Cstring转int、int转Cstring
- Buffer