码迷,mamicode.com
首页 > 其他好文 > 详细

2015.5.18——Excel Sheet Column Number

时间:2016-05-18 23:40:20      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

Excel Sheet Column Number

本题收获:

1.对于字符串中字母转为ASIIC码:string s ;res = s[i]-‘A‘; 这个res就是数字s[i]-‘A‘是对ASIIC的操作。

2.对于进制的转换:利用for循环 ,%,/,数组在完成。

3.2中的数组都是从左到右的,在此题中没有按照高地位

  题目:

  elated to question Excel Sheet Column Title

  Given a column title as appear in an Excel sheet, return its corresponding column number.

  For example:

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28 

  思路:

  我的思路:此题是26进制转换为16进制,但是后面程序具体怎么写没有思路。

  leetcode/dicuss思路:26进制转换为16进制,利用for循环对字符数组遍历。

  代码:给出了大神们写的两种代码,没有追求代码行最短,以干净能看懂为主,提供两种不同思路。

  代码1:利用循环加乘

 1 class Solution 
 2 {
 3 public:
 4     int titleToNumber(string s) 
 5     {
 6         int ret=0;
 7         for(int i=0;i<s.size();i++)    //对字符串从左到右遍历
 8         {
 9             ret*=26;
10             ret+=s[i]-A+1;    //将字符串转化为ASIIC码
11         }
12         return ret;
13     }
14 };

  代码2:利用到幂函数pow(x,y) x的y次方

 1 class Solution {
 2 public:
 3     int titleToNumber(string s) {
 4         int col = 0;
 5         for(int i = s.length(); i > 0; i--) {
 6             col += (s[i - 1] - A + 1) * pow(26, (s.length() - i));
 7         }
 8         return col;
 9     }
10 };

  我的测试代码:把两种思路都写上了

 1 #include "stdafx.h"
 2 #include "iostream"
 3 #include "string"
 4 using namespace std;
 5 
 6 /*思路一
 7 class MyClass
 8 {
 9 public:
10     int titletoNumber(string s)
11     {
12         int res = 0;
13         for (int i = 0; i < s.size(); i++)
14         {
15             res *= 26;
16             res += s[i] - ‘A‘ + 1;
17         }
18         return res;
19     }
20 
21 };*/
22 
23 /*思路二*/
24 class MyClass
25 {
26 public:
27     int titletoNumber(string s)
28     {
29         int res = 0;
30         for (int i = s.size() - 1; i >= 0; i--)
31         {
32             res += s[i] - A + 1 * pow(26, s.size()-i-1);    //AB数组的下标0,1是从左到右的
33         }
34         return res;
35     }
36 };
37 
38 int _tmain(int argc, _TCHAR* argv[])
39 {
40     while (true)
41     {
42         MyClass solution;
43         string s;
44         cin >> s;
45         int m = 0;
46         m = solution.titletoNumber(s);
47         cout << m << endl;
48         system("pause");    //放在while内外都可以
49     }
50     return 0;
51 }

 

2015.5.18——Excel Sheet Column Number

标签:

原文地址:http://www.cnblogs.com/zhuzhu2016/p/5506971.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!