easy +10 pts

Kaprekar number check

Determine if a non-negative integer is a Kaprekar number in base 10.

In number theory, a non-negative integer n is a Kaprekar number in base 10 if its square s = n² can be split into two non-negative parts a (left) and b (right) such that a + b = n, with the condition that b is formed from the rightmost digits of s and a is the remaining left part. For a split to be valid, the right part b must not be zero unless n itself is zero. For example, 9 is a Kaprekar number because 9² = 81 and 8 + 1 = 9. 45 is a Kaprekar number because 45² = 2025 and 20 + 25 = 45. The number 1 is a Kaprekar number because 1² = 1 and we consider the split with a = 0, b = 1 (this is allowed since b ≠ 0). The number 0 is a Kaprekar number by definition. Your task is to write a function `is_kaprekar(n: int) -> bool` that returns `True` if the non-negative integer `n` is a Kaprekar number, and `False` otherwise. Implementation details: - Compute s = n * n. - Convert s to its decimal string representation. Let L be the number of digits in s. - For each possible split length k from 0 to L (where k is the number of digits in the right part b), define: - If k == 0, then b = 0 and a = s. But a split with b = 0 is invalid except when n == 0. - If k > 0, then b = int(s_str[-k:]) and a = int(s_str[:-k]) if s_str[:-k] is not empty, else a = 0. - Check if a + b == n and (b != 0 or n == 0). If any split satisfies both conditions, return True; otherwise False. Do not use any external libraries. The function should handle any non-negative integer up to 10^6.

Constraints

0 ≤ n ≤ 10^6. The function should run in O(d²) time where d is the number of digits of n², which is at most 13, so it is efficient.

Example

>>> is_kaprekar(9)
True
>>> is_kaprekar(45)
True
>>> is_kaprekar(10)
False
>>> is_kaprekar(0)
True
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Generate all possible splits of the string representation of n*n.
For each split, convert the left and right parts back to integers and check the sum.
Remember the special rule about b being zero.
Edge case: n = 0 should return True.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.