Given a string str representing a number, the task is to find whether the number is valid or not if it made topsy-turvy i.e upside-down.
Examples:
Input: str = “1183”
Output: Yes
upside-down(1183) = 1183
Input: str = “983”
Output: No
Approach: Only the digits 1, 3 and 8 are the digits that can form another valid digit when turned upside-down. If the number contains a digit other than these then print No else print Yes.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool topsyTurvy(string str)
{
for ( int i = 0; i < str.length(); i++) {
if (str[i] == '2' || str[i] == '4'
|| str[i] == '5' || str[i] == '6'
|| str[i] == '7' || str[i] == '9' ) {
return false ;
}
}
return true ;
}
int main()
{
string str = "1234" ;
if (topsyTurvy(str))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static boolean topsyTurvy( char [] str)
{
for ( int i = 0 ; i < str.length; i++)
{
if (str[i] == '2' || str[i] == '4' ||
str[i] == '5' || str[i] == '6' ||
str[i] == '7' || str[i] == '9' )
{
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
String str = "1234" ;
if (topsyTurvy(str.toCharArray()))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def topsyTurvy(string) :
for i in range ( len (string)) :
if (string[i] = = '2' or string[i] = = '4' or
string[i] = = '5' or string[i] = = '6' or
string[i] = = '7' or string[i] = = '9' ) :
return False ;
return True ;
if __name__ = = "__main__" :
string = "1234" ;
if (topsyTurvy(string)) :
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG
{
static bool topsyTurvy( char [] str)
{
for ( int i = 0; i < str.Length; i++)
{
if (str[i] == '2' || str[i] == '4' ||
str[i] == '5' || str[i] == '6' ||
str[i] == '7' || str[i] == '9' )
{
return false ;
}
}
return true ;
}
public static void Main(String[] args)
{
String str = "1234" ;
if (topsyTurvy(str.ToCharArray()))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function topsyTurvy( str)
{
for ( var i = 0; i < str.length; i++) {
if (str[i] == '2' || str[i] == '4'
|| str[i] == '5' || str[i] == '6'
|| str[i] == '7' || str[i] == '9' ) {
return false ;
}
}
return true ;
}
var str = "1234" ;
if (topsyTurvy(str))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(|str|)
Auxiliary Space: O(1)