题目描述

Given an integer, return its base 7 string representation.

Example 1:

Input: 100
Output: "202"

Example 2:

Input: -7
Output: "-10"

Note: The input will be in range of [-1e7, 1e7].

解法一

思路

这题就是十进制向七进制的转换,是一种很传统的题目。唯一需要注意的是对负数的处理,即将负数先取正,转换为七进制后再把负号加回去。

Python

class Solution(object):
    def convertToBase7(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num == 0:
            return str(num)
        sign = 1 if num >= 0 else -1
        num = abs(num)
        result = ''
        while num:
            result = str(num % 7) + result
            num //= 7
        return ('-' if sign < 0 else '') + result

Java

public class Solution {
    public String convertToBase7(int num) {
        if (num == 0) {
            return "0";
        }
        int sign = num >= 0 ? 1 : -1;
        num = Math.abs(num);
        StringBuilder builder = new StringBuilder();
        while (num != 0) {
            builder.append(num % 7);
            num /= 7;
        }
        if (sign < 0) {
            builder.append('-');
        }
        return builder.reverse().toString();
    }
}

C++

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

        return (sign < 0 ? "-" : "") + result;
    }
};