Given a number, the task is to check if it is tidy or not. A tidy number is a number whose digits are in non-decreasing order.
Examples :
Input : 1234
Output : Yes
Input : 1243
Output : No
Explanation: Digits “4” and “3” violate the property.
Asked in Freshokartz
Algorithm:
- 1- One by one find all the digits.
- 2- Compare every digit with its next digit.
- 3- If any is in decreasing order then return false.
- 4- Otherwise return true.
Implementation :
C++
#include<iostream>
using namespace std;
bool isTidy( int num)
{
int prev = 10;
while (num)
{
int rem = num % 10;
num /= 10;
if (rem > prev)
return false ;
prev = rem;
}
return true ;
}
int main()
{
int num = 1556;
isTidy(num) ? cout << "Yes"
: cout << "No" ;
return 0;
}
|
Java
class Test
{
static boolean isTidy( int num)
{
int prev = 10 ;
while (num!= 0 )
{
int rem = num % 10 ;
num /= 10 ;
if (rem > prev)
return false ;
prev = rem;
}
return true ;
}
public static void main(String[] args)
{
int num = 1556 ;
System.out.println(isTidy(num) ? "Yes" : "No" );
}
}
|
Python3
def isTidy(num):
prev = 10
while (num):
rem = num % 10
num / = 10
if rem > prev:
return False
prev = rem
return True
num = 1556
if isTidy(num):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool isTidy( int num)
{
int prev = 10;
while (num != 0)
{
int rem = num % 10;
num /= 10;
if (rem > prev)
return false ;
prev = rem;
}
return true ;
}
public static void Main ()
{
int num = 1556;
Console.WriteLine(isTidy(num) ?
"Yes" :
"No" );
}
}
|
PHP
<?php
function isTidy( $num )
{
$prev = 10;
while ( $num )
{
$rem = $num % 10;
$num = (int) $num / 10;
if ( $rem > $prev )
return false;
$prev = $rem ;
}
return true;
}
$num = 1556;
if (isTidy( $num ) == true)
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function isTidy(num)
{
let prev = 10;
while (num!=0)
{
let rem = num % 10;
num /= 10;
if (rem > prev)
return false ;
prev = rem;
}
return true ;
}
let num = 1556;
document.write(isTidy(num) ? "Yes" : "No" );
</script>
|
Time Complexity: O(d) where d is the number of digits in the given number.
Auxiliary Space: O(1) since using constant extra space.
Reference :
https://www.careercup.com/question?id=5136136486780928
This article is contributed by Sahil Chhabra . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.