↓Skip to main content
  1. LeetCode/

LeetCode 3959: Check Good Integer

·1 min· ·
LeetCode Easy Math Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2026-06-14

  • Submissions: Accepted (first try)

Approach
#

squareSum - digitSum splits into a contribution of d² - d per digit. Since d is an integer 0–9, d² - d = d(d - 1) >= 0, so the gap only grows, and once it reaches >= 50 you can return True right away.

My Solution
#

class Solution:
    def checkGoodInteger(self, n: int) -> bool:
        gap = 0
        while n:
            d = n % 10
            gap += d * d - d                 # each digit adds >= 0
            if gap >= 50:
                return True
            n //= 10
        return False

I originally tracked sum_ and sSum separately and compared the difference; a single gap is the same thing.

Complexity
#

Time O(d), space O(1).

Mistakes to Avoid
#

  • An early return needs the running value to be monotonic; if a digit could contribute a negative amount, you could not conclude midway.

Interview Explanation
#

The gap is the sum of d² - d over the digits, which is never negative, so I accumulate as I go and return True at 50, or False after the last digit. Time O(d).

Related

LeetCode 1103: Distribute Candies to People
·1 min
LeetCode Easy Math Simulation
LeetCode 1103 note: simulate the rounds, giving i + 1 candies on the i-th turn, and hand all the rest to the current person when short
LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop
LeetCode 412: Fizz Buzz
·1 min
LeetCode Easy Math String Simulation
LeetCode 412 note: check multiples of 15 first, then 5 and 3; multiples need %, not //
LeetCode 258: Add Digits
·1 min
LeetCode Easy Math Simulation Number-Theory
LeetCode 258 note: sum the digits repeatedly until one remains; the O(1) answer is the digital root 1 + (n - 1) % 9
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 3908: Valid Digit Number
·1 min
LeetCode Easy Math
LeetCode 3908 note: convert to a string and check that it contains x but does not start with x