

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Adding digits of a number using more than 2 methods JavaScript
We are required to write a JavaScript function that in a number and repeatedly sums its digit until it converses to a single digit number.
We will solve this problem by two methods −
Method 1: Using loops
This solution makes use of the while loops to recursively add up the digits of the number.
Example
const num = 123456; const addDigits = (num = 1) => { let sum = num; while(sum % 10 !== sum){ let sum1 = 0; while(sum > 0){ sum1 += sum % 10; sum = Math.floor(sum / 10); } sum = sum1; }; return sum; }; console.log(addDigits(num));
Method 2: Using a constant time solution (O(1) time complexity)
This solution makes use of the Congruence formula of Mathematics, and readers are advised to explore this formula for a better understanding of this solution.
Example
const num = 123456; const addDigits = (num = 1) => { let predicate = (num - 1) % 9; return ++predicate; }; console.log(addDigits(num));
Output
And the output in the console for both methods will be −
3
- Related Questions & Answers
- Recursively adding digits of a number in JavaScript
- Adding methods to Javascript Prototypes
- How to concatenate more than 2 fields with SQL?
- Reversed array of digits from number using JavaScript
- Select rows having more than 2 decimal places in MySQL?
- Separating digits of a number in JavaScript
- Nearest power 2 of a number - JavaScript
- Adding one to number represented as array of digits in C++?
- Prime digits sum of a number in JavaScript
- Digit sum upto a number of digits of a number in JavaScript
- Returning number of digits in factorial of a number in JavaScript
- Recursive product of all digits of a number - JavaScript
- Count of Numbers in Range where the number does not contain more than K non zero digits in C++
- Reverse digits of an integer in JavaScript without using array or string methods
- Program for adding 4 hex digits of a 16-bit number in 8085 Microprocessor
Advertisements