-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddDigits.php
More file actions
47 lines (44 loc) · 930 Bytes
/
Copy pathAddDigits.php
File metadata and controls
47 lines (44 loc) · 930 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
namespace App;
/**
* Add Digits
*
* Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
* Example 1:
* Input: num = 38
* Output: 2
* Explanation: The process is
* 38 --> 3 + 8 --> 11
* 11 --> 1 + 1 --> 2
* Since 2 has only one digit, return it.
*
* https://leetcode.com/problems/add-digits
*/
class AddDigits
{
/**
* @param int $num
* @return int
*/
public function addDigits(int $num): int
{
while ($num >= 10) {
$num = $this->getSumOfDigits($num);
}
return $num;
}
/**
* @param int $number
* @return int
*/
private function getSumOfDigits(int $number): int
{
$sum = 0;
while ($number > 0) {
$remainder = $number % 10;
$number = (int)($number / 10);
$sum += $remainder;
}
return $sum;
}
}