leetcode_168题——Excel Sheet Column Title(数学问题)

Excel Sheet Column Title

  Total Accepted: 25652 Total Submissions: 142582My Submissions

 

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 

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.

 

Hide Tags
  Math
       这道题其实就是将10进制转化为26进制的计算,只是从1开始,而不是从零开始,所以有点搞人,开始的时候想了个笨办法,发现超时了
后来看了下别人的解法
#include<iostream>

#include<string>

#include<math.h>

using namespace std;

/*

string convertToTitle(int n) {

	string str1;

	int i=0;

	int a=n;

	while(1)

	{

		int pinf_i=pow(26.0,i);

		int pinf_ii=pow(26.0,i+1);

		int b;

		if(a<=pinf_ii)

		{b=a/pinf_i;str1.push_back(b+64);break;}



		if(a>pinf_ii)

		{

			if(a%pinf_ii==0)

			{

				str1.push_back('Z');

				a=a-26*pinf_i;

			}

			else

			{

				b=(a%pinf_ii)/pinf_i;

				str1.push_back(b+64);

				a=a-b*pinf_i;

			}

			i++;

		}

	}

	string str2;

	int N=str1.size();

	while(N--)

	{

		str2.push_back(str1.back());

		str1.pop_back();

	}

	return str2;

}

*/

string convertToTitle(int n)

{

	string str1;



	while(n!=0)

	{

		n--;

		str1.push_back(n%26+65);

		n/=26;

	}

	string str2;

	int N=str1.size();

	while(N--)

	{

		str2.push_back(str1.back());

		str1.pop_back();

	}

	return str2;

}



int main()

{

	cout<<convertToTitle(703)<<endl;

}

  

 

你可能感兴趣的:(LeetCode)