• Total Accepted: 12212
  • Total Submissions: 26829
  • Difficulty: Easy
  • Contributors:satyapriya

 

Given an integer, return its base 7 string representation.

Example 1:

Input: 100
Output: "202"

 

Example 2:

Input: -7
Output: "-10"
首先想到的是比较一般的思路:
class Solution {
public:
    string convertToBase7(int num) {
        vector<int> vet;
		int num1;
		string s="";
		if(num==0)
		return s+="0";
		else
		if (num < 0)
		{
			num1 = -num;
			while (num1)
			{
				vet.push_back(num1 % 7);
				num1 = num1 / 7;
			}
			s = "-";
			for (int i = vet.size()-1; i >= 0; i--)
			{
				s += to_string(vet[i]);
			}
		}
		else
		{
			while (num)
			{
				vet.push_back(num % 7);
				num = num / 7;
			}
			for (int i = vet.size() - 1; i >= 0; i--)
			{
				s += to_string(vet[i]);
			}
		}
		return s;
    }
};

  接下来,就是改进:

class Solution {
public:
    string convertToBase7(int num) {
        string result;
        int anum = abs(num);
        while(anum >= 7) {
            result = to_string(anum%7) + result;
            anum /= 7;
        }
        result = to_string(anum) + result;
        
        if(num < 0) {
            result = "-" + result;
        }
        return result;
    }
};

  

posted on 2017-05-05 18:05  无惧风云  阅读(275)  评论(0编辑  收藏  举报