From adaaf8b744b17c4dd4c2cb029a9d4f6d5bc9f589 Mon Sep 17 00:00:00 2001 From: ahmedgamal2212 Date: Wed, 26 Apr 2023 17:44:42 +0200 Subject: [PATCH] Add solution to day 26 --- .../26- Add Digits (Ahmed Gamal).js | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 04- April/26- Add Digits/26- Add Digits (Ahmed Gamal).js diff --git a/04- April/26- Add Digits/26- Add Digits (Ahmed Gamal).js b/04- April/26- Add Digits/26- Add Digits (Ahmed Gamal).js new file mode 100644 index 000000000..5f40dcb5d --- /dev/null +++ b/04- April/26- Add Digits/26- Add Digits (Ahmed Gamal).js @@ -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; +}; \ No newline at end of file