给定三个整数A , B和N ,将以下过程重复N次:
- 向A添加一个数字,以便在添加之后, A被B整除。
- 在上述操作的N次迭代之后,打印可能的最小值A。
- 如果操作失败,则打印-1 。
注意:每添加一位数字后,我们需要检查可除性。
例子:
Input: A = 10, B = 11, N = 1
Output: -1
No matter what digit you add, 10X will never be divisible by 11.
Input: A = 5, B = 3, N = 3
Output: 5100
方法:将第一个数字从0到9进行暴力破解,如果没有一个数字使A被B整除,则答案为-1 。否则,添加满足条件的第一个数字,然后在(n-1)次之后添加0 ,因为如果A被B整除,那么A * 10,A * 100,…也将被B整除。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
int addNDigits(int a, int b, int n)
{
int num = a;
// Try all digits from (0 to 9)
for (int i = 0; i <= 9; i++) {
int tmp = a * 10 + i;
if (tmp % b == 0) {
a = tmp;
break;
}
}
// Fails in the first move itself
if (num == a)
return -1;
// Add (n-1) 0's
for (int j = 0; j < n - 1; j++)
a *= 10;
return a;
}
// Driver Program to test above function
int main()
{
int a = 5, b = 3, n = 3;
cout << addNDigits(a, b, n);
return 0;
}
Java
//Java implementation of the approach
import java.io.*;
class GFG {
static int addNDigits(int a, int b, int n)
{
int num = a;
// Try all digits from (0 to 9)
for (int i = 0; i <= 9; i++) {
int tmp = a * 10 + i;
if (tmp % b == 0) {
a = tmp;
break;
}
}
// Fails in the first move itself
if (num == a)
return -1;
// Add (n-1) 0's
for (int j = 0; j < n - 1; j++)
a *= 10;
return a;
}
// Driver Program to test above function
public static void main (String[] args) {
int a = 5, b = 3, n = 3;
System.out.print( addNDigits(a, b, n));
}
}
// This code is contributed by anuj_67..
Python3
# Python3 implementation of the approach
def addNDigits(a, b, n) :
num = a
# Try all digits from (0 to 9)
for i in range(10) :
tmp = a * 10 + i
if (tmp % b == 0) :
a = tmp
break
# Fails in the first move itself
if (num == a) :
return -1
# Add (n-1) 0's
for j in range(n - 1) :
a *= 10
return a
# Driver Code
if __name__ == "__main__" :
a = 5
b = 3
n = 3
print(addNDigits(a, b, n))
# This code is contributed by Ryuga
C#
// C# implementation of the approach
using System;
class GFG
{
static int addNDigits(int a,
int b, int n)
{
int num = a;
// Try all digits from (0 to 9)
for (int i = 0; i <= 9; i++)
{
int tmp = a * 10 + i;
if (tmp % b == 0)
{
a = tmp;
break;
}
}
// Fails in the first move itself
if (num == a)
return -1;
// Add (n-1) 0's
for (int j = 0; j < n - 1; j++)
a *= 10;
return a;
}
// Driver Code
public static void Main ()
{
int a = 5, b = 3, n = 3;
Console.WriteLine(addNDigits(a, b, n));
}
}
// This code is contributed
// by anuj_67..
PHP
输出:
5100