JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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:

  • -10^7 <= num <= 10^7

Code

class Solution {
    public String convertToBase7(int num) {
        if(num == 0) return "0";
        
        StringBuilder sb = new StringBuilder();
        
        if(num < 0){
            return "-" + convertToBase7(-num);
        }
        
        while(num != 0){
            sb.append(num % 7);
            num /= 7;
        }
        
        return sb.reverse().toString();
    }
}