168. Excel Sheet Column Title
来源:互联网 发布:linux上如何卸载mysql 编辑:程序博客网 时间:2024/05/23 11:45
168. Excel Sheet Column Title
Description:
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
Example:
1 -> A 2 -> B 3 -> C ...26 -> Z27 -> AA28 -> AB
Analysis:
这个问题跟十进制转换为26进制数是比较类似的,但是有点细微差别(你会发现 A、B…、AA、AB这些数里没有“0”,Z而非A0表示26)。
1. 首先注意,我们使用(num-1)%26+1来取得低位数,而非直接使用num%26,因为后者会把‘26’变为‘0’
2. 在取高位的时候,我们使用(num-1)/26,这样可以防止’26’的整数倍进位。
note: 由于个人使用的C++编译器版本较低,以下代码中string::insert函数使用的比较费劲,C++11版本好像可以直接在其函数中使用char类型参数了(详见:http://en.cppreference.com/w/cpp/string/basic_string/insert)。
Source Code(C++):
#include <iostream>#include <string>#include <cmath>using namespace std;class Solution {public: string convertToTitle(int n) { string s; s = (char)((n-1)%26+65); while (n>26) { n =(n-1)/26; char c = (char)((n-1)%26+65); s.insert(0, &c, 0, 1); } return s; }};int main() { Solution sol; cout << sol.convertToTitle(27); return 0;}
0 0
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title
- 168. Excel Sheet Column Title *
- 168. Excel Sheet Column Title
- Vector源码注释,粗略理解
- 深入理解JVM03--内存分配与回收策略
- mysql慢查询分析
- 树的遍历
- Java的消息对话框
- 168. Excel Sheet Column Title
- Android百度定位API的使用
- Http1.0、Spdy和Http2.0的对比
- matlab 矢量化编程(二)—— 使用 meshgrid
- 图文解说:Nginx+tomcat配置集群负载均衡
- 冒泡排序
- hdu4710 Balls Rearrangement(数学公式+取模)
- 简单立体几何和DP的结合
- HDU 1052田忌赛马 贪心+动态数组