leetcode----字母二十六进制与十进制数之间的转化

 字母二十六进制与十进制数之间的转化

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
	//二十六进制转成十进制
	int titleToNumber(string s) {
		int n = s.size();
		int res = 0;
		int tmp = 1;
		for (int i = n; i >= 1; --i) {
			res += (s[i - 1] - 'a') * tmp; //n=1个位;n=2十位*26,26进制
			tmp *= 26;
		}
		return res;
	}
	//十进制转成二十六进制
	string NumberTotitle(int cols){
		string res;
		while (cols > 0)
		{
			int m = cols % 26;
			if (m == 0) m = 26;
			res = (char)(m + 'a') + res;
			cols = (cols - m) / 26;
		}
		return res;
	}
};

void  main()
{
	string s1, s2;
	cout << "请输入第一个字母" << endl;
	getline(cin, s1);//读入string1
	cout << "请输入第二个字母" << endl;
	getline(cin, s2);//读入string2
	Solution So;
	int count = 0;
	int count1 = So.titleToNumber(s1);
	int count2 = So.titleToNumber(s2);
	count = count1 + count2;
	string res = So.NumberTotitle(count);
	cout << res << endl;
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/weixin_40807247/article/details/82430022