1. Description
Given an integer num, return a string of its base 7 representation.
constraints :
- \(-10^{7}\) <= num <= \(10^{7}\)
2. Algorithms
- Start
- Declare variable named sign initialized to 1.
- If num is smaller than zero, assign -1 to sign.
- Declare variable named digits initialized to empty list.
- Repeat the steps until num == 0 :
- Append remainder of num divide 7 to digits.
- Update num as num mod 7.
- If sign is -1, append "-" to digits.
- Return reverse joined digits.
- End
3. Codes
class Solution:
def convertToBase7(self, num: int) -> str:
sign = 1
if num < 0 : sign = -1
if num == 0 : return "0"
num *= sign
digits = []
while num > 0 :
digits.append(str(num % 7))
num //= 7
if sign == -1 :
digits.append("-")
return "".join(reversed(digits))
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
507 Perfect Number (0) | 2022.09.03 |
---|---|
506 Relative Ranks (0) | 2022.09.03 |
501 Find Mode in Binary Search Tree (0) | 2022.09.02 |
500 Keyboard Row (0) | 2022.09.02 |
496 Next Greater Element I (0) | 2022.09.01 |