Skip to content

3959. Check Good Integer

Description

You are given a positive integer n.

Let digitSum be the sum of the digits of n, and let squareSum be the sum of the squares of the digits of n.

An integer is called good if squareSum - digitSum >= 50.

Return true if n is good. Otherwise, return false.

Β 

Example 1:

Input: n = 1000

Output: false

Explanation:

  • The digits of 1000 are 1, 0, 0, and 0.
  • The digitSum is 1 + 0 + 0 + 0 = 1.
  • The squareSum is 12 + 02 + 02 + 02 = 1.
  • The squareSum - digitSum is 1 - 1 = 0. As 0 is not greater than or equal to 50, the output is false.

Example 2:

Input: n = 19

Output: true

Explanation:

  • The digits of 19 are 1 and 9.
  • The digitSum is 1 + 9 = 10.
  • The squareSum is 12 + 92 = 1 + 81 = 82.
  • The squareSum - digitSum is 82 - 10 = 72. As 72 is greater than or equal to 50, the output is true.

Β 

Constraints:

  • 1 <= n <= 109

Solutions

Solution 1: Simulation

We use a variable \(s\) to record the result of the square sum minus the digit sum of \(n\). If \(s\) is greater than or equal to 50, we return \(\textit{true}\); otherwise, we return \(\textit{false}\).

The time complexity is \(O(\log n)\), where \(\log n\) is the number of digits in \(n\). The space complexity is \(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;
}

Comments