0504. Base 7

504. Base 7 #

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:

  • -10000000 <= num <= 10000000

Summary #

Given an integer num, convert it to base 7 and output it as a string.

Solution Approach #

Repeatedly divide num by 7, then reverse the remainders

Code #

package leetcode

import "strconv"

func convertToBase7(num int) string {
	if num == 0 {
		return "0"
	}
	negative := false
	if num < 0 {
		negative = true
		num = -num
	}
	var ans string
	var nums []int
	for num != 0 {
		remainder := num % 7
		nums = append(nums, remainder)
		num = num / 7
	}
	if negative {
		ans += "-"
	}
	for i := len(nums) - 1; i >= 0; i-- {
		ans += strconv.Itoa(nums[i])
	}
	return ans
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文