Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Digit distance of two numbers - JavaScript
We are required to write a JavaScript function that takes in two numbers a and b returns their digit distance.
Digit distance
The digit distance of two numbers is the absolute sum of the difference between their corresponding digits.
For example: If the numbers are −
345 678
Then the digit distance will be −
|3-6| + |4-7| + |5-8| = 3 + 3 + 3 = 9
Example
Following is the code −
const num1 = 345;
const num2 = 678;
const digitDistance = (a, b) => {
const aStr = String(a);
const bStr = String(b);
let diff = 0;
for(let i = 0; i < aStr && i < bStr.length; i++){
diff += Math.abs(+(aStr[i] || 0) - +(bStr[i] || 0));
};
return diff;
};
console.log(digitDistance(num1, num2));
Output
Following is the output in the console −
9
Advertisements