Digit distance of two numbers - JavaScript

We are required to write a JavaScript function that takes in two numbers and returns their digit distance.

What is Digit Distance?

The digit distance of two numbers is the absolute sum of the difference between their corresponding digits from left to right.

For example, if the numbers are:

345
678

Then the digit distance calculation will be:

|3-6| + |4-7| + |5-8| = 3 + 3 + 3 = 9

Implementation

Here's how to calculate digit distance in JavaScript:

const num1 = 345;
const num2 = 678;

const digitDistance = (a, b) => {
    const aStr = String(a);
    const bStr = String(b);
    let diff = 0;
    
    // Get the maximum length to handle numbers of different lengths
    const maxLength = Math.max(aStr.length, bStr.length);
    
    for(let i = 0; i < maxLength; i++){
        // Use 0 as default for missing digits
        const digitA = +(aStr[i] || 0);
        const digitB = +(bStr[i] || 0);
        diff += Math.abs(digitA - digitB);
    }
    
    return diff;
};

console.log(digitDistance(num1, num2));
9

Handling Different Length Numbers

The function also works correctly when numbers have different lengths:

console.log(digitDistance(123, 45));    // |1-0| + |2-4| + |3-5| = 1 + 2 + 2 = 5
console.log(digitDistance(9, 123));     // |0-1| + |0-2| + |9-3| = 1 + 2 + 6 = 9
console.log(digitDistance(100, 999));   // |1-9| + |0-9| + |0-9| = 8 + 9 + 9 = 26
5
9
26

How It Works

The function converts both numbers to strings, then iterates through each digit position. For missing digits in shorter numbers, it uses 0 as the default value. The absolute difference between corresponding digits is calculated and summed up.

Conclusion

Digit distance provides a way to measure how different two numbers are digit by digit. This implementation handles numbers of any length by padding shorter numbers with zeros.

Updated on: 2026-03-15T23:18:59+05:30

409 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements