Check if a number is formed by Concatenation of 1, 14 or 144 only
Given a number . The task is to check if the number is formed by concatenating the numbers 1, 14 and 144 only any number of times and in any order.
If it is possible, print YES otherwise print NO.
Example:
Input: N = 141411
Output: YES
Input: N = 14134
Output: NO
The idea is to fetch single digit, double digit and triple digit numbers from the end and check if any of them matches with 1, 14 and 144 respectively. If any of them matches, divide the number with that and repeat the above step until the number is greater than zero.
Below is the implementation of using above approach:
C++
#include <iostream>
using namespace std;
string checkNumber( int N)
{
int temp = N;
while (temp > 0) {
if (temp % 1000 == 144)
temp /= 1000;
else if (temp % 100 == 14)
temp /= 100;
else if (temp % 10 == 1)
temp /= 10;
else {
return "NO" ;
}
}
return "YES" ;
}
int main()
{
int N = 1414;
cout << checkNumber(N);
return 0;
}
|
Java
import java.io.*;
class GFG {
static String checkNumber( int N)
{
int temp = N;
while (temp > 0 ) {
if (temp % 1000 == 144 )
temp /= 1000 ;
else if (temp % 100 == 14 )
temp /= 100 ;
else if (temp % 10 == 1 )
temp /= 10 ;
else {
return "NO" ;
}
}
return "YES" ;
}
public static void main (String[] args) {
int N = 1414 ;
System.out.println(checkNumber(N));
}
}
|
Python 3
def checkNumber(N):
temp = N
while (temp > 0 ):
if (temp % 1000 = = 144 ):
temp / = 1000
elif (temp % 100 = = 14 ):
temp / = 100
elif (temp % 10 = = 1 ):
temp / = 10
else :
return "YES"
return "NO"
N = 1414 ;
print (checkNumber(N));
|
C#
using System;
class GFG {
static String checkNumber( int N)
{
int temp = N;
while (temp > 0) {
if (temp % 1000 == 144)
temp /= 1000;
else if (temp % 100 == 14)
temp /= 100;
else if (temp % 10 == 1)
temp /= 10;
else {
return "NO" ;
}
}
return "YES" ;
}
public static void Main () {
int N = 1414;
Console.WriteLine(checkNumber(N));
}
}
|
PHP
<?php
function checkNumber( $N )
{
$temp = $N ;
while ( $temp > 0)
{
if ( $temp % 1000 == 144)
$temp /= 1000;
else if ( $temp % 100 == 14)
$temp /= 100;
else if ( $temp % 10 == 1)
$temp /= 10;
else
{
return "YES" ;
}
}
return "NO" ;
}
$N = 1414;
echo checkNumber( $N );
?>
|
Javascript
<script>
function checkNumber(N)
{
let temp = N;
while (temp > 0) {
if (temp % 1000 == 144)
temp = parseInt(temp / 1000, 10);
else if (temp % 100 == 14)
temp = parseInt(temp / 100, 10);
else if (temp % 10 == 1)
temp = parseInt(temp / 10, 10);
else {
return "NO" ;
}
}
return "YES" ;
}
let N = 1414;
document.write(checkNumber(N));
</script>
|
Time Complexity: O(logn)
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
15 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...