Show problems as
Classic problem #2698MediumMathBacktracking

Find the Punishment Number of an Integer

Real-world version: Adding Up the Balanced Squares
Tracked in this browser only
Read Find the Punishment Number of an Integer on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A whole number i is balanced when the decimal digits of i * i can be cut into consecutive blocks whose values add up to i. For instance 9 is balanced, because 81 cuts into 8 and 1, which add to 9.

Return the total of i * i taken over every balanced i from 1 to n.

Examples

Example 1

Input
n = 9
Output
82

Below ten only 1 and 9 are balanced: 1 is its own square, and 81 cuts into 8 and 1. Their squares add to 82.

Example 2

Input
n = 2
Output
1

The square 4 cannot be cut into blocks adding to 2, so only 1 counts.

Example 3

Input
n = 45
Output
3503

The balanced numbers up to 45 are 1, 9, 10, 36 and 45. The last of them counts because 2025 cuts into 20 and 25.

Constraints

  • 1 <= n <= 1000

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def punishment_number(n: int) -> int:
Java
public int punishmentNumber(int n)