LeetCode 1556. Thousand Separator
Published in
Mar 14, 2021
題目:
在數字千位位置加一個string的點。
Example 1:
Input: n = 987
Output: "987"
Example 2:
Input: n = 1234
Output: "1.234"
Example 3:
Input: n = 123456789
Output: "123.456.789"
Example 4:
Input: n = 0
Output: "0"
思路:
- 因為是return 一個string format,因此initial
result = " " - input的integer先轉換成string format
n = str(n) - count =0 每數三個加一個點
- 讀string由右往左讀,因此最後一位的index 是len(n)-1
for i in range(len(n)-1,-1,-1): - if count < 3:
result = n[i] +result 注意這邊的位置 n[i]先
count +=1 - if count ==3 and i ≥1:
result = “.” +result
count = 0 - return result
Coding:
class Solution:
def thousandSeparator(self, n: int) -> str:
result =''
n = str(n)
count = 0
for i in range(len(n)-1, -1,-1):
if count < 3:
result = n[i] + result
count += 1
if count == 3 and i >= 1:
result = '.' + result
count = 0
return result