Created
August 20, 2017 07:24
-
-
Save farkwun/db5f45de230c7b0445a71fdc75c02287 to your computer and use it in GitHub Desktop.
504. Base 7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://leetcode.com/problems/base-7/description/ | |
class Solution(object): | |
BASE_EXP = [1, 7, 49, 343, 2401, 16807, 117649, 823543, 5764801, 40353607] | |
def convertToBase7(self, num): | |
""" | |
:type num: int | |
:rtype: str | |
""" | |
def add_x_to_digits(x, digit_list): | |
list_ptr = 0 | |
lsd = digit_list[list_ptr] | |
carry = 1 if (lsd + x) > 6 else 0 | |
if carry == 0: | |
digit_list[list_ptr] += x | |
return | |
while carry == 1: | |
if list_ptr >= len(digit_list): | |
digit_list.append(0) | |
digit = digit_list[list_ptr] | |
digit += x | |
if digit > 6: | |
digit -= 7 | |
carry = 1 | |
else: | |
carry = 0 | |
x = carry | |
digit_list[list_ptr] = digit | |
list_ptr += 1 | |
neg = True if num < 0 else False | |
num = abs(num) | |
digits = [0] * 10 | |
i = len(digits) - 1 | |
rem = 0 | |
while i > 0: | |
digits[i] = num//self.BASE_EXP[i] | |
rem = num % self.BASE_EXP[i] | |
if digits[i] > 0: | |
num = rem | |
i -= 1 | |
digits[i] = rem | |
digits = digits[::-1] | |
for i in range(len(digits)): | |
digits[i] = str(digits[i]) | |
ret_str = str(int(''.join(digits))) | |
if neg: | |
ret_str = "-" + ret_str | |
return ret_str |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment