leetcode-504-easy

Base 7

Given an integer num, return a string of its base 7 representation.

Example 1:

Input: num = 100
Output: "202"
Example 2:

Input: num = -7
Output: "-10"
Constraints:

-107 <= num <= 107

思路一: 辗转相除法,负数先转成正数再计算

public String convertToBase7(int num) {
    if (num == 0) return "0";

    StringBuilder result = new StringBuilder();

    boolean negative = num < 0;
    num = Math.abs(num);
    while (num != 0) {
        result.append(num % 7);
        num /= 7;
    }

    return negative ?
             "-" + result.reverse() :
            result.reverse().toString();
}
posted @ 2022-10-24 17:53  iyiluo  阅读(15)  评论(0)    收藏  举报