Corner digit number difference - JavaScript

We are required to write a JavaScript function that takes in a number, constructs a new number from the first and last digit of that number and returns the difference between the original number and the number thus formed.

For example: If the input is 34567

Then the corner digits number will be:

37

And the output will be:

34530

Algorithm

The solution involves extracting the first and last digits, combining them to form a corner number, then calculating the difference.

Example

Following is the code:

const num = 34567;

const cornerDifference = num => {
    let temp = Math.abs(num);
    let corner = temp % 10; // Get last digit
    
    if (temp < 100) {
        corner = temp;
    } else {
        while (temp >= 10) {
            temp = Math.floor(temp / 10);
        }
        corner = (temp * 10) + corner; // Combine first and last digits
    }
    
    return num - corner;
};

console.log(cornerDifference(num));

Output

Following is the output in the console:

34530

Testing with Multiple Examples

// Test different cases
console.log("Number: 34567, Difference:", cornerDifference(34567));
console.log("Number: 123, Difference:", cornerDifference(123));
console.log("Number: 89, Difference:", cornerDifference(89));
console.log("Number: 5, Difference:", cornerDifference(5));
Number: 34567, Difference: 34530
Number: 123, Difference: 110
Number: 89, Difference: 0
Number: 5, Difference: 0

How It Works

The function handles three cases:

  • Single digit: Returns 0 (corner number equals original)
  • Two digits: Returns 0 (corner number equals original)
  • Three or more digits: Extracts first and last digit, combines them, then calculates the difference

Conclusion

This function efficiently extracts corner digits and calculates the difference. It handles edge cases like single and two-digit numbers by returning zero difference.

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

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements