给定两个整数A和B ,任务是检查两个数字是否具有相等的位数。
例子:
Input: A = 12, B = 1
Output: No
Input: A = 20, B = 99
Output: Yes
方法:当两个数字均大于0时,将两个数字均除以10。最后,检查两个数字是否均为0。如果其中任何一个都不为0,则它们的数字位数不相等。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function that return true if A and B
// have same number of digits
bool sameLength(int A, int B)
{
while (A > 0 && B > 0) {
A = A / 10;
B = B / 10;
}
// Both must be 0 now if
// they had same lengths
if (A == 0 && B == 0)
return true;
return false;
}
// Driver code
int main()
{
int A = 21, B = 1;
if (sameLength(A, B))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG
{
// Function that return true if A and B
// have same number of digits
static boolean sameLength(int A, int B)
{
while ((A > 0) && (B > 0))
{
A = A / 10;
B = B / 10;
}
// Both must be 0 now if
// they had same lengths
if ((A == 0 )&& (B == 0))
return true;
return false;
}
// Driver code
public static void main (String[] args)
{
int A = 21, B = 1;
if (sameLength(A, B))
System.out.println ("Yes");
else
System.out.println("No");
}
}
// This code is contributed by @tushil.
Python3
# Python implementation of the approach
# Function that return true if A and B
# have same number of digits
def sameLength(A, B):
while (A > 0 and B > 0):
A = A / 10;
B = B / 10;
# Both must be 0 now if
# they had same lengths
if (A == 0 and B == 0):
return True;
return False;
# Driver code
A = 21; B = 1;
if (sameLength(A, B)):
print("Yes");
else:
print("No");
# This code contributed by PrinciRaj1992
C#
// C# implementation of the approach
using System;
class GFG
{
// Function that return true if A and B
// have same number of digits
static bool sameLength(int A, int B)
{
while ((A > 0) && (B > 0))
{
A = A / 10;
B = B / 10;
}
// Both must be 0 now if
// they had same lengths
if ((A == 0 )&& (B == 0))
return true;
return false;
}
// Driver code
static public void Main ()
{
int A = 21, B = 1;
if (sameLength(A, B))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by ajit..
输出:
No