- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- Recursively adding digits of a number in JavaScript
- Using the number line represent -2 more than -4.
- Adding methods to Javascript Prototypes
- Using the number line write the integer which is :(a) 3 more than 5(b) 5 more than $–5$(c) 6 less than 2(d) 3 less than $–2$
- Using the number line, write the integer which is(i) 4 more than 6(ii) 5 more than ( -6 )(iii) 6 less than 2(iv) 2 less than ( -3 )
- Reversed array of digits from number using JavaScript
- Reverse digits of an integer in JavaScript without using array or string methods
- A two-digit number is 3 more than 4 times the sum of its digits. If 18 is added to the number, the digits are reversed. Find the number.
- A two-digit number is 4 more than 6 times the sum of its digits. If 18 is subtracted from the number, the digits are reversed. Find the number.
- Using the number line write the integer which is :(a) 3 more than 5(b) 5 more than –5
- Separating digits of a number in JavaScript
- Adding one to number represented as array of digits in C++?
- Program for adding 4 hex digits of a 16-bit number in 8085 Microprocessor
- Sum of individual even and odd digits in a string number using JavaScript
- Prime digits sum of a number in JavaScript

Advertisements