Skip to content

Commit a74dbb0

Browse files
committed
Add solution #2698
1 parent 6e83c7e commit a74dbb0

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,7 @@
582582
2693|[Call Function with Custom Context](./2693-call-function-with-custom-context.js)|Medium|
583583
2694|[Event Emitter](./2694-event-emitter.js)|Medium|
584584
2695|[Array Wrapper](./2695-array-wrapper.js)|Easy|
585+
2698|[Find the Punishment Number of an Integer](./2698-find-the-punishment-number-of-an-integer.js)|Medium|
585586
2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy|
586587
2704|[To Be Or Not To Be](./2704-to-be-or-not-to-be.js)|Easy|
587588
2705|[Compact Object](./2705-compact-object.js)|Medium|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 2698. Find the Punishment Number of an Integer
3+
* https://leetcode.com/problems/find-the-punishment-number-of-an-integer/
4+
* Difficulty: Medium
5+
*
6+
* Given a positive integer n, return the punishment number of n.
7+
*
8+
* The punishment number of n is defined as the sum of the squares of all integers i such that:
9+
* - 1 <= i <= n
10+
* - The decimal representation of i * i can be partitioned into contiguous substrings such that
11+
* the sum of the integer values of these substrings equals i.
12+
*/
13+
14+
/**
15+
* @param {number} n
16+
* @return {number}
17+
*/
18+
var punishmentNumber = function(n) {
19+
function canPartition(num, target, start) {
20+
if (!target && start === num.length) {
21+
return true;
22+
} else if (start >= num.length) {
23+
return false;
24+
}
25+
for (let i = start, sum = 0; i < num.length; i++) {
26+
sum = sum * 10 + +num[i];
27+
if (sum > target) {
28+
break;
29+
} else if (canPartition(num, target - sum, i + 1)) {
30+
return true;
31+
}
32+
}
33+
34+
return false;
35+
}
36+
37+
let result = 0;
38+
for (let i = 1; i <= n; i++) {
39+
if (canPartition((i * i).toString(), i, 0)) {
40+
result += i * i;
41+
}
42+
}
43+
44+
return result;
45+
};

0 commit comments

Comments
 (0)