algorithm notes: leetcode#504 base 7

Problem


Solution


Initial thoughts

Python implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class :
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if not num:
return str(num)
n = abs(num)
res = ""
while n:
res = str(n%7)+res
n = n//7
return res if num > 0 else "-"+res

Java implementation

1
2
3
4
5
6
7
8
9
10
11
12
class {
public String convertToBase7(int num) {
if(num==0){ return "0"; }
int n = Math.abs(num);
String res = "";
while(n>0){
res = Integer.toString(n%7)+res;
n /= 7;
}
return num > 0? res : "-"+res;
}
}

504. Base 7
(中文版) 算法笔记: 力扣#504 七进制数