Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f865981

Browse files
committed
2698
1 parent 1c63922 commit f865981

File tree

1 file changed

+50
-0
lines changed
  • Medium/2698. Find the Punishment Number of an Integer

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
class Solution
3+
{
4+
/**
5+
* @param Integer $n
6+
* @return Integer
7+
*/
8+
public function punishmentNumber($n)
9+
{
10+
$sum = 0;
11+
12+
for ($i = 0; $i <= $n; $i++) {
13+
14+
$squareNumber = $i * $i;
15+
16+
if ($this->canPunish((string) $squareNumber, 0, $i)) {
17+
$sum += $squareNumber;
18+
}
19+
}
20+
return $sum;
21+
}
22+
23+
private function canPunish($s, $start, $target)
24+
{
25+
if ($start == strlen($s)) {
26+
return $target == 0;
27+
}
28+
29+
$num = 0;
30+
for ($i = $start; $i < strlen($s); $i++) {
31+
$num = $num * 10 + (int) $s[$i];
32+
33+
if ($num > $target) {
34+
break;
35+
}
36+
37+
if ($this->canPunish($s, $i + 1, $target - $num)) {
38+
return true;
39+
}
40+
}
41+
42+
return false;
43+
}
44+
}
45+
46+
$solution = new Solution();
47+
48+
$result = $solution->punishmentNumber(10);
49+
50+
echo $result; // Output: 144

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /