Wednesday, 27 Oct 2021

# Check if all the digits of the given number are same

Given a positive integer N, the task is to check whether all the digits of the given integer N are the same or not. If found to be true, then print Yes. Otherwise, print No.Examples:Input: N = 222Output: YesInput: N = 232Output: NoNaive Approach: The simplest approach to solve the given problem is to iterate over all the digits of the given number N and if there exists any distinct digit then print Yes. Otherwise, print No.Below is the implementation of the above approach:Java  import java.io.*;  class GFG {              public static String checkSameDigits(int N)    {                int digit = N % 10;          while (N != 0) {                          int current_digit = N % 10;                          N = N / 10;                                      if (current_digit != digit) {                return “No”;            }        }                  return “Yes”;    }          public static void main(String args[])        throws IOException    {        int N = 222;        System.out.println(            checkSameDigits(N));    }}Output:
Yes
Time Complexity: O(log10N)Auxiliary Space: O(1)Efficient Approach: The above approach can also be optimized by forming another number, say M of the same length of the given number N with the rightmost digit of N assuming N has all same digits and then comparing it with N. Now, M is of type (K*111….), where K is any digit from N.Now to create the number M consisting of the only 1s, the sum of a Geometric Progression can be used as illustrated for the count of digits as 3:Consider the first term(say a) as 1 and the common ratio(say r) as 10. Now for the value count of digits(say D) as 3 the sum of Geometric Progression is given by:=> Sum =  => Sum =   => Sum =   -> Sum = 111From the above observations, generate the number M and check if K*M is the same as the N or not. If found to be true, then print Yes. Otherwise, print No.Below is the implementation of the above approach:Java  import java.io.*;  class GFG {              public static String checkSameDigits(int N)    {                int length = ((int)Math.log10(N)) + 1;                                  int M = ((int)Math.pow(10, length) – 1)                / (10 – 1);        M *= N % 10;                  if (M == N)            return “Yes”;                  return “No”;    }          public static void main(String args[])        throws IOException    {        int N = 222;        System.out.println(            checkSameDigits(N));    }}Output:
Yes
Time Complexity: O(1)Auxiliary Space: O(1)Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.