7/23 每日一題(7進制)
Given an integer num, return a string of its base 7 representation.
Example 1:
Input: num = 100 Output: "202"
Example 2:
Input: num = -7 Output: "-10"
Constraints:
-107 <= num <= 107
class Solution:
def convertToBase7(self, num: int) -> str:
if num==0:
return '0'
n=abs(num)
res=[]
while n>0:
number=n%7
res.append(str(number))
n//=7 #繼續計算下一位直到個位數
if num < 0:
res.append('-')#負號還回去
res.reverse()#翻轉list
return ''.join(res)
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁