Number with even sum of digits
Last Updated :
14 Feb, 2023
Fixed compiling error in java programA positive integer is considered a good number if sum of its digits is even. Find n-th smallest good number.
Examples :
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
A simple solution is to start from 1 and traverse through all-natural numbers. For every number x, check if sum of digits is even. If even increment count of good numbers. Finally, return the n-th Good number.
An efficient solution is based on a pattern in the answer. Let us list down first 20 good numbers. The first 20 good numbers are: 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, 28, 31, 33, 35, 37, 39, 40. Observe that if last digit of n is from 0 to 4 the answer is 2*n and if last digit of n is from 5 to 9 the answer is 2*n + 1.
Steps to solve this problem:
1. Declare a variable lastdig=n%10.
2. Check if lastdig is greater than zero and smaller than 4 than return n<<1.
3. Else return (n<<1)+1.
C++
#include <bits/stdc++.h>
using namespace std;
long long int findKthGoodNo( long long int n)
{
int lastDig = n % 10;
if (lastDig >= 0 && lastDig <= 4)
return n << 1;
else
return (n << 1) + 1;
}
int main()
{
long long int n = 10;
cout << findKthGoodNo(n);
return 0;
}
|
Java
import java.io.*;
public class GFG
{
static int findKthGoodNo( int n)
{
int lastDig = n % 10 ;
if (lastDig >= 0 && lastDig <= 4 )
return n << 1 ;
else
return (n << 1 ) + 1 ;
}
public static void main(String[] args)
{
int n = 10 ;
System.out.println(findKthGoodNo(n));
}
}
|
Python 3
def findKthGoodNo(n):
lastDig = n % 10
if (lastDig > = 0 and lastDig < = 4 ) :
return n << 1
else :
return (n << 1 ) + 1
n = 10
print (findKthGoodNo(n))
|
C#
using System;
class GFG
{
public static int findKthGoodNo( int n)
{
int lastDig = n % 10;
if (lastDig >= 0 && lastDig <= 4)
return n << 1;
else
return (n << 1) + 1;
}
static public void Main ( string []args)
{
int n = 10;
Console.WriteLine(findKthGoodNo(n));
}
}
|
PHP
<?php
function findKthGoodNo( $n )
{
$lastDig = $n % 10;
if ( $lastDig >= 0 && $lastDig <= 4)
return $n << 1;
else
return ( $n << 1) + 1;
}
$n = 10;
echo (findKthGoodNo( $n ));
?>
|
Javascript
<script>
function findKthGoodNo(n)
{
let lastDig = n % 10;
if (lastDig >= 0 && lastDig <= 4)
return n << 1;
else
return (n << 1) + 1;
}
let n = 10;
document.write(findKthGoodNo(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...