forked from 7oSkaaa/LeetCode_DailyChallenge_2023
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5c128df
commit adaaf8b
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
// Autor: Ahmed Gamal | ||
|
||
// the idea for this solution is so simple, we will loop until the number is less than 10 | ||
// in each iteration we will calculate the sum of the digits of the number | ||
|
||
/** | ||
* @param {number} num | ||
* @return {number} | ||
*/ | ||
var addDigits = function(num) { | ||
// loop until the number is less than 10 | ||
while(num > 10) { | ||
// calculate the sum of the digits of the number | ||
// x: copy of the number to not change the original number | ||
// sum: the sum of the digits of the number | ||
|
||
// loop until the number is 0 | ||
// in each iteration we will add the last digit to the sum | ||
// and remove the last digit from the number | ||
|
||
let x = num, sum = 0; | ||
while(x) { | ||
sum += x % 10; | ||
x = Math.floor(x / 10); | ||
} | ||
|
||
// update the number with the sum | ||
num = sum; | ||
} | ||
|
||
// return the number | ||
return num; | ||
}; |