w3resource

JavaScript: Check whether all the digits in a given number are the same or not

JavaScript Basic: Exercise-140 with Solution

Check if All Digits in Number Are Same

Write a JavaScript program to check whether all the digits in a given number are the same or not.

Visual Presentation:

JavaScript: Check whether all the digits in a given number are the same or not.

Sample Solution:

JavaScript Code:

/**
 * Function to test if all digits in the number are the same
 * @param {number} num - The input number
 * @returns {boolean} - Returns true if all digits are the same, false otherwise
 */
function test_same_digit(num) {
  var first = num % 10; // Extracting the last digit as a reference
  while (num) {
    if (num % 10 !== first) return false; // Checking if the current digit is different from the reference
    num = Math.floor(num / 10); // Removing the last digit by integer division
  }
  return true; // Returning true if all digits are the same
}

console.log(test_same_digit(1234)); // Output: false
console.log(test_same_digit(1111)); // Output: true
console.log(test_same_digit(22222222)); // Output: true 

Output:

false
true
true

Live Demo:

See the Pen javascript-basic-exercise-140 by w3resource (@w3resource) on CodePen.

Flowchart:

Flowchart: JavaScript - Check whether all the digits in a given number are the same or not

ES6 Version:

/**
 * Function to test if all digits in the number are the same
 * @param {number} num - The input number
 * @returns {boolean} - Returns true if all digits are the same, false otherwise
 */
const test_same_digit = (num) => {
  let first = num % 10; // Extracting the last digit as a reference
  while (num) {
    if (num % 10 !== first) return false; // Checking if the current digit is different from the reference
    num = Math.floor(num / 10); // Removing the last digit by integer division
  }
  return true; // Returning true if all digits are the same
};

console.log(test_same_digit(1234)); // Output: false
console.log(test_same_digit(1111)); // Output: true
console.log(test_same_digit(22222222)); // Output: true

Improve this sample solution and post your code through Disqus.

Previous: JavaScript program to find the position of a rightmost round number in an array of integers. Returns 0 if there are no round number.
Next: JavaScript program to find the number of elements which presents in both of the given arrays.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-140.php