如果正整数的数字总和为偶数,则认为该整数是一个好数字。查找第n个最小的有效数。
例子 :
Input : n = 1
Output : 2
First good number is smallest positive
number with sum of digits even which is 2.
Input : n = 10
Output : 20
一个简单的解决方案是从1开始遍历所有自然数。对于每个数字x,请检查数字的总和是否为偶数。如果偶数增加好数。最后返回第n个好数字。
一个有效的解决方案基于答案中的模式。让我们列出前20个好数字。前20个有效数字为:2、4、6、8、11、13、15、17、19、20、22、24、26、28、31、33、35、37、39、40。 n的最后一位数字是0到4,答案是2 * n;如果n的最后一位数字是5到9,答案是2 * n + 1。
C++
// C++ program to find n-th
// Good number.
#include
using namespace std;
// Function to find kth good number.
long long int findKthGoodNo(long long int n)
{
// Find the last digit of n.
int lastDig = n % 10;
// If last digit is between
// 0 to 4 then return 2 * n.
if (lastDig >= 0 && lastDig <= 4)
return n << 1;
// If last digit is between
// 5 to 9 then return 2*n + 1.
else
return (n << 1) + 1;
}
// Driver code
int main()
{
long long int n = 10;
cout << findKthGoodNo(n);
return 0;
}
Java
// Java program to find n-th
// Good number.
class GFG
{
// Function to find kth good number.
static int findKthGoodNo(int n)
{
// Find the last digit of n.
int lastDig = n % 10;
// If last digit is between
// 0 to 4 then return 2*n.
if (lastDig >= 0 && lastDig <= 4)
return n << 1;
// If last digit is between
// 5 to 9 then return 2*n + 1.
else
return (n << 1) + 1;
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.println(findKthGoodNo(n));
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python 3
# Python 3 program to find
# n-th Good number.
# Function to find kth
# good number.
def findKthGoodNo(n):
# Find the last digit of n.
lastDig = n % 10
# If last digit is between
# 0 to 4 then return 2 * n.
if (lastDig >= 0 and lastDig <= 4) :
return n << 1
# If last digit is between
# 5 to 9 then return 2 * n + 1.
else:
return (n << 1) + 1
# Driver code
n = 10
print(findKthGoodNo(n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to find n-th
// Good number.
using System;
class GFG
{
// Function to find kth
// good number
public static int findKthGoodNo(int n)
{
// Find the last digit of n.
int lastDig = n % 10;
// If last digit is between
// 0 to 4 then return 2*n.
if (lastDig >= 0 && lastDig <= 4)
return n << 1;
// If last digit is between
// 5 to 9 then return 2*n + 1.
else
return (n << 1) + 1;
}
// Driver code
static public void Main (string []args)
{
int n = 10;
Console.WriteLine(findKthGoodNo(n));
}
}
// This code is contributed by Ajit.
PHP
= 0 && $lastDig <= 4)
return $n << 1;
// If last digit is between
// 5 to 9 then return 2*n + 1.
else
return ($n << 1) + 1;
}
// Driver code
$n = 10;
echo(findKthGoodNo($n));
// This code is contributed by Ajit.
?>
Javascript
输出:
20
时间复杂度: O(1)
辅助空间: O(1)