给定一个整数 。任务是找到另一个n的整数,该整数可以被3整除,但不能被6整除。假设n被6整除,如果不可能,则打印-1。
例子:
Input: n = 336
Output: 363
Input: n = 48
Output: -1
对于要被6整除的数,它必须被3以及2整除,这意味着每个被3整除的偶数整数都可以被6整除。因此,可以被3整除但不能被6整除的整数是可以被3整除的奇数整数。
因此,如果整数n包含任何奇数整数,则存在可以被3整除但不能被6整除的置换,否则不存在这种置换。
算法:
- 令LEN为整数长度(即ceil(log10(n)))。
- 遍历LEN并检查n是偶数还是奇数。
- 如果n为奇数,则返回n
- 否则,将n旋转一次。并继续。
- 如果LEN超过返回-1
下面是上述方法的实现:
C++
// C++ program to find permutation of n
// which is divisible by 3 but not
// divisible by 6
#include
using namespace std;
// Function to find the permutation
int findPermutation(int n)
{
// length of integer
int len = ceil(log10(n));
for (int i = 0; i < len; i++) {
// if integer is even
if (n % 2 != 0) {
// return odd integer
return n;
}
else {
// rotate integer
n = (n / 10) + (n % 10) * pow(10, len - i - 1);
continue;
}
}
// return -1 in case no required
// permutation exists
return -1;
}
// Driver Code
int main()
{
int n = 132;
cout << findPermutation(n);
return 0;
}
Java
// Java program to find permutation
// of n which is divisible by 3
// but not divisible by 6
import java.lang.*;
import java.util.*;
class GFG
{
// Function to find the permutation
static int findPermutation(int n)
{
// length of integer
int len = (int)Math.ceil(Math.log10(n));
for (int i = 0; i < len; i++)
{
// if integer is even
if (n % 2 != 0)
{
// return odd integer
return n;
}
else
{
// rotate integer
n = (n / 10) + (n % 10) *
(int)Math.pow(10, len - i - 1);
continue;
}
}
// return -1 in case no required
// permutation exists
return -1;
}
// Driver Code
public static void main(String args[])
{
int n = 132;
System.out.println(findPermutation(n));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
Python3
# Python3 program to find permutation
# of n which is divisible by 3 but
# not divisible by 6
from math import log10, ceil, pow
# Function to find the permutation
def findPermutation(n):
# length of integer
len = ceil(log10(n))
for i in range(0, len, 1):
# if integer is even
if n % 2 != 0:
# return odd integer
return n
else:
# rotate integer
n = ((n / 10) + (n % 10) *
pow(10, len - i - 1))
continue
# return -1 in case no required
# permutation exists
return -1
# Driver Code
if __name__ == '__main__':
n = 132
print(int(findPermutation(n)))
# This code is contributed
# by Surendra_Gangwar
C#
// C# program to find permutation
// of n which is divisible by 3
// but not divisible by 6
using System;
class GFG
{
// Function to find the permutation
static int findPermutation(int n)
{
// length of integer
int len = (int)Math.Ceiling(Math.Log10(n));
for (int i = 0; i < len; i++)
{
// if integer is even
if (n % 2 != 0)
{
// return odd integer
return n;
}
else
{
// rotate integer
n = (n / 10) + (n % 10) *
(int)Math.Pow(10, len - i - 1);
continue;
}
}
// return -1 in case no required
// permutation exists
return -1;
}
// Driver Code
public static void Main()
{
int n = 132;
Console.WriteLine(findPermutation(n));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
PHP
输出:
213