Algorithm
Problem Name: 504. Base 7
Problem Link: https://leetcode.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:
-107 <= num <= 107
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public String convertToBase7(int num) {
StringBuilder sb = new StringBuilder();
char sign = num < 0 ? '-' : ' ';
num = Math.abs(num);
while (num > 0) {
sb.append(num % 7);
num /= 7;
}
String representation = sb.length() == 0 ? "0" : sb.reverse().toString();
if (sign == '-') {
return sign + representation;
}
return representation;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const convertToBase7 = function(num) {
if(num == null) return ''
const sign = num >= 0 ? '+' : '-'
let res = ''
let remain = Math.abs(num)
if(num === 0) return '0'
while(remain > 0) {
res = remain % 7 + res
remain = Math.floor(remain / 7)
}
return sign === '+' ? res : '-' + res
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def convertToBase7(self, num):
lead = "" if num > 0 else "0" if num == 0 else "-"
res, num = [], abs(num)
while num:
res.append(int(num % 7))
num //= 7
return lead + "".join(str(c) for c in res[::-1])
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System.Linq;
using System.Text;
namespace LeetCode
{
public class _0504_Base7
{
public string ConvertToBase7(int num)
{
if (num == 0) return "0";
var signal = num < 0;
if (num < 0) num = -num;
var sb = new StringBuilder();
while (num > 0)
{
sb.Append((num % 7).ToString());
num /= 7;
}
if (signal)
sb.Append('-');
return new string(sb.ToString().Reverse().ToArray());
}
}
}
Copy The Code &
Try With Live Editor
Input
Output