当前位置:网站首页>LeetCode1556. Thousand separated number

LeetCode1556. Thousand separated number

2022-07-06 16:43:00 Daylight629

1556. Thousands of separators

Give you an integer n, Please add points every three ( namely “.” Symbol ) As a thousand separator , And return the result 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"

Tips :

  • 0 <= n < 2^31

Two 、 Method 1

simulation , Pay attention to do-while , Because there are test cases equal to 0 Of

class Solution {
    
    public String thousandSeparator(int n) {
    
        int count = 0;
        StringBuilder res = new StringBuilder();
        do {
    
            int cnt = n % 10;
            n /= 10;
            count++;
            res.append(cnt);
            if (count % 3 == 0 && n != 0) {
    
                res.append('.');
            }
        } while (n != 0);
        res.reverse();
        return res.toString();
    }
}

Complexity analysis

  • Time complexity :O(logn).
  • Spatial complexity :O(logn).
原网站

版权声明
本文为[Daylight629]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131315404178.html