LeetCode 1556. Thousand Separator

題目:

在數字千位位置加一個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"

思路:

  1. 因為是return 一個string format,因此initial
    result = " "
  2. input的integer先轉換成string format
    n = str(n)
  3. count =0 每數三個加一個點
  4. 讀string由右往左讀,因此最後一位的index 是len(n)-1
    for i in range(len(n)-1,-1,-1):
  5. if count < 3:
    result = n[i] +result 注意這邊的位置 n[i]先
    count +=1
  6. if count ==3 and i ≥1:
    result = “.” +result
    count = 0
  7. 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

--

--

Sharko Shen
Data Science & LeetCode for Kindergarten

Thinking “Data Science for Beginners” too hard for you? Check out “Data Science for Kindergarten” !