-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbase-7.cpp
More file actions
31 lines (29 loc) · 746 Bytes
/
base-7.cpp
File metadata and controls
31 lines (29 loc) · 746 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Time: O(1)
// Space: O(1)
class Solution {
public:
string convertToBase7(int num) {
if (num < 0) {
return string("-").append(convertToBase7(-num));
}
string result;
while (num) {
result.append(to_string(num % 7));
num /= 7;
}
reverse(result.begin(), result.end());
return result.empty() ? "0" : result;
}
};
class Solution2 {
public:
string convertToBase7(int num) {
if (num < 0) {
return string("-").append(convertToBase7(-num));
}
if (num < 7) {
return to_string(num);
}
return convertToBase7(num / 7).append(to_string(num % 7));
}
};