2016.5.19——Excel Sheet Column Title

Excel Sheet Column Title

本题收获:

1.由int型转换为整型(string),如何转化, res = 'A'+(n-1)%26和之前由A-z转化为十进制相反,res = s[i]-'A'+1.(为什么有+1,-1还有点迷糊,貌似是十进制是0-9,26进制是)

2.十进制到26进制转化

  题目: 

  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 

  思路:

    我的思路:十进制转化为26进制,但是不知道怎么将数字转化为字母

         或者利用hash映射

    leetcode/discuss思路:思路1:十进制转化为26进制

               思路2:有hash的,但是看上去比较复杂

  代码:

  代码1:思路1代码

1 string convertToTitle(int n) {
2     string res="";
3     while(n>0){
4         res=char('A'+(n-1)%26)+res;    //将数字转化为字母,每次加的上个res位置要在右边,如果是res+char(),则高地位发生变化
5         n=(n-1)/26;
6     }
7     return res;
8 }

  注意:1.数字转化为字母

     2.高地位

  举例来看代码:

    28(AB)  第一次循环: res =  'A' + 1= B  n = 1

            第二次循环:res = 'A' + 0 +B = AB  n = 0   

           结束循环 返回AB

  0位减1的原因:假如输入的数字为A  那么第一次循环 结果应该为 res = 'A' 

         如果没有减1 那么第一次循环结果为 res = 'A' + 1 = 'B' 出错。

  代码2:思路2

  我的测试代码:代码有main函数

  

 1 #include "stdafx.h"
 2 #include "iostream"
 3 #include "string"
 4 using namespace std;
 5 
 6 class MyClass
 7 {
 8 public:
 9     string coverttoTitle(int n)
10     {
11         string res = "";
12         while (n)
13         {
14             res = char('A' + (n - 1) % 26) + res;
15             n = (n - 1) / 26;
16         }
17         return res;
18     }
19 };
20 
21 
22 int _tmain(int argc, _TCHAR* argv[])
23 {
24     int n;
25     while (true)
26     {
27         cin >> n;
28         string m;
29         MyClass solution;
30         m = solution.coverttoTitle(n);    //第一次将m定义成了int型,出错:error C2440: “=”: 无法从“std::string”转换为“int”
31         cout << m << endl;
32     }
33         system("pause");
34         return 0;
35 }

  运行结果:

  

  中间出现错误:

    错误提示为:error C2440: “=”: 无法从“std::string”转换为“int” 

    出错原因:没有搞清楚各个参数的类型,n为从主函数传递到类整数的int型,m为从类中返回的结果是字母为string型

 

posted on 2016-05-19 23:00  zhuzhu2016  阅读(191)  评论(0编辑  收藏  举报

导航