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

LeetCode—Excel Sheet Column Title

时间:2015-01-28 14:37:56      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:leetcode   excel sheet column t   

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 
这里就是一个将数字转化为字母的部分,其实就是一个将10进制转化为26进制

#include <string>
using namespace std;

	string convertToTitle(int n) {
		int i,j,mod;
		string s;
		char num;
		while(n>0)
		{
			n--;
			mod=n%26;
			num='A'+mod;
			s=num+s;
			n=n/26;
		}
		return s;
	}

void main()
{
	string x = convertToTitle(28);
}

反过来还有个相关的问题:

For example:

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

这里主要的问题是在将string当中的元素一个个取出来,可以利用像数组一样的方法

#include <string>
using namespace std;

int titleToNumber(string s) {
	int length = s.size();
	int retVal = 0;
	for(int i = 0; i < length; i++)
	{
		int x = (s[i]-'A')+1;
		retVal =retVal*26+x;
	}
	return retVal;
}

void main()
{
	int x = titleToNumber("AB");
}


LeetCode—Excel Sheet Column Title

标签:leetcode   excel sheet column t   

原文地址:http://blog.csdn.net/xietingcandice/article/details/43230043

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