leetcode 1556. Thousand Separator(python)

362 阅读1分钟

描述

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"

Example 5:

Note:

0 <= n < 2^31

解析

根据题意,就是讲数字 n ,转换成字符串,然后从后往前,每隔三位用点隔开,然后返回新的字符串即可。

解答

class Solution(object):
    def thousandSeparator(self, n):
        """
        :type n: int
        :rtype: str
        """
        s = str(n)
        res = []
        for i in range(len(s), -1, -3):
            tmp = s[max(0, i - 3):i]
            if tmp:
                res.insert(0, tmp)
        return ".".join(res)
        	      
		

运行结果

Runtime: 12 ms, faster than 94.03% of Python online submissions for Thousand Separator.
Memory Usage: 13.4 MB, less than 38.06% of Python online submissions for Thousand Separator.

原题链接:leetcode.com/problems/th…

您的支持是我最大的动力