Check if two numbers have same number of digits
Given two integers A and B, the task is to check whether both the numbers have an equal number of digits.
Examples:
Input: A = 12, B = 1
Output: No
Input: A = 20, B = 99
Output: Yes
Approach: While both the numbers are > 0, keep dividing both the numbers by 10. Finally, check if both the numbers are 0. If any one of them is not 0 then they had an unequal numbers of digits.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool sameLength( int A, int B)
{
while (A > 0 && B > 0) {
A = A / 10;
B = B / 10;
}
if (A == 0 && B == 0)
return true ;
return false ;
}
int main()
{
int A = 21, B = 1;
if (sameLength(A, B))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static boolean sameLength( int A, int B)
{
while ((A > 0 ) && (B > 0 ))
{
A = A / 10 ;
B = B / 10 ;
}
if ((A == 0 )&& (B == 0 ))
return true ;
return false ;
}
public static void main (String[] args)
{
int A = 21 , B = 1 ;
if (sameLength(A, B))
System.out.println ( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def sameLength(A, B):
while (A > 0 and B > 0 ):
A = A / 10 ;
B = B / 10 ;
if (A = = 0 and B = = 0 ):
return True ;
return False ;
A = 21 ; B = 1 ;
if (sameLength(A, B)):
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG
{
static bool sameLength( int A, int B)
{
while ((A > 0) && (B > 0))
{
A = A / 10;
B = B / 10;
}
if ((A == 0 )&& (B == 0))
return true ;
return false ;
}
static public void Main ()
{
int A = 21, B = 1;
if (sameLength(A, B))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function sameLength(A, B)
{
while (A > 0 && B > 0) {
A = parseInt(A / 10);
B = parseInt(B / 10);
}
if (A == 0 && B == 0)
return true ;
return false ;
}
let A = 21, B = 1;
if (sameLength(A, B))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(log10(min(A, B)))
Auxiliary Space: O(1)
Last Updated :
31 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...