mirror of https://github.com/doocs/leetcode.git
|
…
|
||
|---|---|---|
| .. | ||
| README.md | ||
| README_EN.md | ||
| Solution.cpp | ||
| Solution.go | ||
| Solution.java | ||
| Solution.py | ||
| Solution.rs | ||
| Solution.ts | ||
README_EN.md
| comments | difficulty | edit_url | tags | ||
|---|---|---|---|---|---|
| true | Easy | https://github.com/doocs/leetcode/edit/main/solution/0500-0599/0504.Base%207/README_EN.md |
|
504. Base 7
Description
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
Solutions
Solution 1
Python3
class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0:
return '0'
if num < 0:
return '-' + self.convertToBase7(-num)
ans = []
while num:
ans.append(str(num % 7))
num //= 7
return ''.join(ans[::-1])
Java
class Solution {
public String convertToBase7(int num) {
if (num == 0) {
return "0";
}
if (num < 0) {
return "-" + convertToBase7(-num);
}
StringBuilder sb = new StringBuilder();
while (num != 0) {
sb.append(num % 7);
num /= 7;
}
return sb.reverse().toString();
}
}
C++
class Solution {
public:
string convertToBase7(int num) {
if (num == 0) return "0";
if (num < 0) return "-" + convertToBase7(-num);
string ans = "";
while (num) {
ans = to_string(num % 7) + ans;
num /= 7;
}
return ans;
}
};
Go
func convertToBase7(num int) string {
if num == 0 {
return "0"
}
if num < 0 {
return "-" + convertToBase7(-num)
}
ans := []byte{}
for num != 0 {
ans = append([]byte{'0' + byte(num%7)}, ans...)
num /= 7
}
return string(ans)
}
TypeScript
function convertToBase7(num: number): string {
if (num == 0) {
return '0';
}
let res = '';
const isMinus = num < 0;
if (isMinus) {
num = -num;
}
while (num != 0) {
const r = num % 7;
res = r + res;
num = (num - r) / 7;
}
return isMinus ? '-' + res : res;
}
Rust
impl Solution {
pub fn convert_to_base7(mut num: i32) -> String {
if num == 0 {
return String::from("0");
}
let mut res = String::new();
let is_minus = num < 0;
if is_minus {
num = -num;
}
while num != 0 {
res.push_str((num % 7).to_string().as_str());
num /= 7;
}
if is_minus {
res.push('-');
}
res.chars().rev().collect()
}
}