From 0de6b2993b0be018626c5600e4b3343cd21e2867 Mon Sep 17 00:00:00 2001 From: tphyhFighting <2363176358@qq.com> Date: Mon, 7 Mar 2022 10:40:37 +0800 Subject: [PATCH] add: leetcode 0504 readme --- leetcode/0504.Base-7/README.md | 60 ++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 leetcode/0504.Base-7/README.md diff --git a/leetcode/0504.Base-7/README.md b/leetcode/0504.Base-7/README.md new file mode 100644 index 00000000..7b77d714 --- /dev/null +++ b/leetcode/0504.Base-7/README.md @@ -0,0 +1,60 @@ +# [504. Base 7](https://leetcode-cn.com/problems/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:** + +- -10000000 <= num <= 10000000 + +## 题目大意 + +给定一个整数 num,将其转化为 7 进制,并以字符串形式输出。 + +## 解题思路 + + num反复除以7,然后倒排余数 + +# 代码 + +```go +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 +} +``` \ No newline at end of file