跳转至

3959. 判定好整数

题目描述

给你一个正整数 n

digitSum 表示 n 的各位数字之和,令 squareSum 表示 n 的各位数字平方之和。

如果一个整数满足 squareSum - digitSum >= 50,则称它是 好整数 

如果 n 是好整数,返回 true;否则,返回 false

 

示例 1:

输入: n = 1000

输出: false

解释:

  • 1000 的数字为 1、0、0 和 0。
  • digitSum1 + 0 + 0 + 0 = 1
  • squareSum12 + 02 + 02 + 02 = 1
  • squareSum - digitSum1 - 1 = 0。由于 0 小于 50,因此输出 false

示例 2:

输入: n = 19

输出: true

解释:

  • 19 的数字为 1 和 9。
  • digitSum1 + 9 = 10
  • squareSum12 + 92 = 1 + 81 = 82
  • squareSum - digitSum82 - 10 = 72。由于 72 大于等于 50,因此输出 true

 

提示:

  • 1 <= n <= 109

解法

方法一:模拟

我们用一个变量 \(s\) 来记录 \(n\) 的各位数字的平方和减去各位数字之和的结果,如果 \(s\) 大于等于 50,则返回 \(\textit{true}\),否则返回 \(\textit{false}\)

时间复杂度 \(O(\log n)\),其中 \(\log n\) 是数字 \(n\) 的位数。空间复杂度 \(O(1)\)

1
2
3
4
5
6
7
class Solution:
    def checkGoodInteger(self, n: int) -> bool:
        s = 0
        while n:
            n, x = divmod(n, 10)
            s += x * (x - 1)
        return s >= 50
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    public boolean checkGoodInteger(int n) {
        int s = 0;
        for (; n > 0; n /= 10) {
            int x = n % 10;
            s += x * (x - 1);
        }
        return s >= 50;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
public:
    bool checkGoodInteger(int n) {
        int s = 0;
        for (; n > 0; n /= 10) {
            int x = n % 10;
            s += x * (x - 1);
        }
        return s >= 50;
    }
};
1
2
3
4
5
6
7
8
func checkGoodInteger(n int) bool {
    s := 0
    for ; n > 0; n /= 10 {
        x := n % 10
        s += x * (x - 1)
    }
    return s >= 50
}
1
2
3
4
5
6
7
8
function checkGoodInteger(n: number): boolean {
    let s: number = 0;
    for (; n; n = Math.floor(n / 10)) {
        const x = n % 10;
        s += x * (x - 1);
    }
    return s >= 50;
}

评论