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:
digitSum is 1 + 0 + 0 + 0 = 1.squareSum is 12 + 02 + 02 + 02 = 1.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:
digitSum is 1 + 9 = 10.squareSum is 12 + 92 = 1 + 81 = 82.squareSum - digitSum is 82 - 10 = 72. As 72 is greater than or equal to 50, the output is true.
Constraints:
1 <= n <= 109Problem Overview: You are given an integer and must determine whether it is a good integer. A number is considered good if every digit in the number is identical. For example, 7, 111, and 9999 are good integers, while 123 or 101 are not.
Approach 1: Digit Extraction with Modulo (O(d) time, O(1) space)
Extract digits one by one using modulo and division. Store the last digit using n % 10. Then repeatedly divide the number by 10 and compare each extracted digit with the stored one. If any digit differs, the integer is not good. This method works directly on the numeric representation without converting to another data type. It is memory efficient and relies on basic arithmetic operations.
Approach 2: String Comparison (O(d) time, O(d) space)
Convert the integer to a string and compare each character with the first character. Iterate through the string and return false as soon as a mismatch appears. This approach is simpler to read and implement, especially in high-level languages. The tradeoff is a small additional memory cost due to the string conversion.
Both approaches involve a single pass through the digits. The number of digits d is log10(n), so the runtime grows linearly with digit count. Problems like this frequently appear when practicing strings manipulation or math based digit processing. The digit extraction technique is also common in number theory style interview questions.
Recommended for interviews: The digit extraction approach using modulo and division is usually preferred. It shows you understand how numbers are represented and avoids unnecessary conversions. Mentioning the string-based alternative demonstrates awareness of readability tradeoffs, but the arithmetic method highlights stronger problem-solving fundamentals.
Solutions for this problem are being prepared.
Try solving it yourself| Approach | Time | Space | When to Use |
|---|---|---|---|
| Digit Extraction with Modulo | O(d) | O(1) | Best general solution when working directly with integers and minimizing memory |
| String Comparison | O(d) | O(d) | When readability and quick implementation matter more than strict memory usage |
Practice Check Good Integer with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor