2698: Find-the-Punishment-Number-of-an-Integer
Medium
table of contents
Because of the light constraints, I realised you can just recurse over all the possible partitions.
To do this:
code
class Solution {
public:
int checkForSum(int current_sum, int target_sum, int sqbare) {
int power = 0;
int ans = 0;
while (square > 0) {
current_sum += (square%10)*pow(10, power);
square /= 10;
if (current_sum == target_sum && square == 0) {
return 1;
} else if (current_sum <= target_sum) {
ans |= checkForSum(current_sum, target_sum, square);
}
++power;
}
return ans;
}
int punishmentNumber(int n) {
int ans = 0;
for (int i = 1; i <= n; ++i) {
int square = i*i;
if (checkForSum(0, i, square) == 1) {
ans += square;
}
}
return ans;
}
};