Skip to content

Commit 68d8191

Browse files
committed
Added Base 7
1 parent 0024d62 commit 68d8191

File tree

4 files changed

+93
-0
lines changed

4 files changed

+93
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <string>
2+
#include <algorithm>
3+
4+
class Solution {
5+
public:
6+
std::string convertToBase7(int num) {
7+
if (num == 0) {
8+
return "0";
9+
}
10+
11+
int originalNum = num;
12+
num = abs(num);
13+
std::string remainders;
14+
15+
while (num > 0) {
16+
int remainder = num % 7;
17+
remainders.push_back(remainder + '0');
18+
num /= 7;
19+
}
20+
21+
if (originalNum < 0) {
22+
remainders.push_back('-');
23+
}
24+
25+
std::reverse(remainders.begin(), remainders.end());
26+
return remainders;
27+
}
28+
};
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
public class Solution {
2+
public String convertToBase7(int num) {
3+
if (num == 0) {
4+
return "0";
5+
}
6+
7+
int originalNum = num;
8+
num = Math.abs(num);
9+
StringBuilder remainders = new StringBuilder();
10+
11+
while (num > 0) {
12+
int remainder = num % 7;
13+
remainders.append(remainder);
14+
num /= 7;
15+
}
16+
17+
if (originalNum < 0) {
18+
remainders.append('-');
19+
}
20+
21+
return remainders.reverse().toString();
22+
}
23+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
var convertToBase7 = function(num) {
2+
if (num === 0) {
3+
return '0';
4+
}
5+
6+
var originalNum = num;
7+
num = Math.abs(num);
8+
var remainders = [];
9+
10+
while (num > 0) {
11+
var remainder = num % 7;
12+
remainders.push(String(remainder));
13+
num = Math.floor(num / 7);
14+
}
15+
16+
if (originalNum < 0) {
17+
remainders.push('-');
18+
}
19+
20+
remainders.reverse();
21+
return remainders.join('');
22+
};
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution:
2+
def convertToBase7(self, num: int) -> str:
3+
if num == 0:
4+
return '0'
5+
6+
original_num = num
7+
num = abs(num)
8+
remainders = []
9+
10+
while num > 0:
11+
remainder = num % 7
12+
remainders.append(str(remainder))
13+
num //= 7
14+
15+
if original_num < 0:
16+
remainders.append('-')
17+
remainders.reverse()
18+
return ''.join(remainders)
19+
20+
# Time and Space: O(log_7(N))

0 commit comments

Comments
 (0)