관리 메뉴

솜씨좋은장씨

[leetCode] 1556. Thousand Separator (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 1556. Thousand Separator (Python)

솜씨좋은장씨 2020. 8. 29. 21:44
728x90
반응형

Given an integer n, add a dot (".") as the thousands separator and return it in string format.

 

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"

Constraints:

  • 0 <= n < 2^31

Solution

class Solution:
    def thousandSeparator(self, n: int) -> str:
        if len(str(n)) < 4:
            return str(n)
        else:
            len_str = len(str(n))
            loop_num = len_str // 3
            
            mod_num_list = []
            
            for i in range(loop_num):
                n_mod_1000 = n % 1000
                
                if n_mod_1000 < 100:
                    mod_num_list.append('0' + str(n_mod_1000))
                else:
                    mod_num_list.append(str(n_mod_1000))
                
                n = n // 1000
            if n != 0:
                mod_num_list.append(str(n))
                
            mod_num_list_reverse = mod_num_list[::-1]
            
            answer = '.'.join(mod_num_list_reverse)
            
            return answer

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments