Medium
Given a positive integer n
, return the punishment number of n
.
The punishment number of n
is defined as the sum of the squares of all integers i
such that:
1 <= i <= n
i * i
can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i
.Example 1:
Input: n = 10
Output: 182
Explanation: There are exactly 3 integers i that satisfy the conditions in the statement:
Hence, the punishment number of 10 is 1 + 81 + 100 = 182
Example 2:
Input: n = 37
Output: 1478
Explanation: There are exactly 4 integers i that satisfy the conditions in the statement:
Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478
Constraints:
1 <= n <= 1000
public class Solution {
public int punishmentNumber(int n) {
return calculatePunishmentNumber(n);
}
private boolean partition(int x, int target) {
if (x == target) {
return true;
}
if (target < 0 || x < target) {
return false;
}
return partition(x / 10, target - (x % 10))
|| partition(x / 100, target - (x % 100))
|| partition(x / 1000, target - (x % 1000));
}
private int calculatePunishmentNumber(int n) {
int res = 0;
for (int i = 1; i <= n; i++) {
int iSq = i * i;
if (partition(iSq, i)) {
res += iSq;
}
}
return res;
}
}