Open In App

Check if a given number is Fancy

Last Updated : 27 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A fancy number is one which when rotated 180 degrees is the same. Given a number, find whether it is fancy or not.
180 degree rotations of 6, 9, 1, 0 and 8 are 9, 6, 1, 0 and 8 respectively
Examples: 
 

Input:  num =  96
Output: Yes
If we rotate given number by 180, we get same number

Input:  num =  916
Output: Yes
If we rotate given number by 180, we get same number

Input:  num =  996
Output: No

Input:  num =  121
Output: No

We strongly recommend you to minimize your browser and try this yourself first.
The idea is to create a map to store fancy pair mappings. After creating map, traverse given number from both ends and if at any point characters at current ends are not fancy pairs, return false. This algorithm is similar to palindrome check algorithm.

Below is the implementation of above idea:

C++




// C++ program to find if a given number is fancy or not.
#include<bits/stdc++.h>
using namespace std;
 
bool isFancy(string& num)
{
    // To store mappings of fancy pair characters. For example
    // 6 is paired with 9 and 9 is paired with 6.
    map<char, char> fp;
    fp['0'] = '0';
    fp['1'] = '1';
    fp['6'] = '9';
    fp['8'] = '8';
    fp['9'] = '6';
 
    // Find number of digits in given number
    int n = num.length();
 
    // Traverse from both ends, and compare characters one by one
    int l = 0, r = n-1;
    while (l<=r)
    {
        // If current characters at both ends are not fancy pairs
        if (fp.find(num[l]) == fp.end() || fp[num[l]] != num[r])
            return false;
        l++;
        r--;
    }
    return true;
}
 
// Driver program
int main()
{
    string str = "9088806";
    isFancy(str)? cout << "Yes": cout << "No";
    return 0;
}


Java




// Java program to find if a given number
// is fancy or not
import java.util.*;
 
class GFG
{
static boolean isFancy(String num)
{
    // To store mappings of fancy pair characters.
    // For example 6 is paired with 9 and 9 is paired with 6.
    Map<Character,
        Character> fp = new HashMap<Character,
                                    Character>();
                                     
    fp. put('0', '0');
    fp. put('1', '1');
    fp. put('6', '9');
    fp. put('8', '8');
    fp. put('9', '6');
 
    // Find number of digits in given number
    int n = num.length();
 
    // Traverse from both ends,
    // and compare characters one by one
    int l = 0, r = n-1;
    while (l <= r)
    {
        // If current characters at both ends
        // are not fancy pairs
        if (!fp.containsKey(num.charAt(l)) ||
             fp.get(num.charAt(l)) != num.charAt(r))
            return false;
        l++;
        r--;
    }
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "9088806";
    if(isFancy(str))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by PrinciRaj1992


Python3




# Python 3 program to find if a given number is fancy or not.
def isFancy(num):
 
    # To store mappings of fancy pair characters. For example
    # 6 is paired with 9 and 9 is paired with 6.
    fp = {}
    fp['0'] = '0'
    fp['1'] = '1'
    fp['6'] = '9'
    fp['8'] = '8'
    fp['9'] = '6'
 
    # Find number of digits in given number
    n = len(num)
 
    # Traverse from both ends, and compare characters one by one
    l = 0
    r = n-1
    while (l <= r):
 
        # If current characters at both ends are not fancy pairs
        if (num[l] not in fp or fp[num[l]] != num[r]):
            return False
        l += 1
        r -= 1
    return True
 
# Driver program
if __name__ == "__main__":
 
    st = "9088806"
    if isFancy(st):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by ukasp.


C#




// C# program to find if a given number
// is fancy or not
using System;
using System.Collections.Generic;
 
class GFG
{
static bool isFancy(String num)
{
    // To store mappings of fancy pair characters.
    // For example 6 is paired with 9 and 9 is paired with 6.
    Dictionary<char, char> fp = new Dictionary<char, char>();
                                     
    fp.Add('0', '0');
    fp.Add('1', '1');
    fp.Add('6', '9');
    fp.Add('8', '8');
    fp.Add('9', '6');
 
    // Find number of digits in given number
    int n = num.Length;
 
    // Traverse from both ends,
    // and compare characters one by one
    int l = 0, r = n - 1;
    while (l <= r)
    {
        // If current characters at both ends
        // are not fancy pairs
        if (!fp.ContainsKey(num[l]) ||
             fp[num[l]] != num[r])
            return false;
        l++;
        r--;
    }
    return true;
}
 
// Driver Code
public static void Main(String[] args)
{
    String str = "9088806";
    if(isFancy(str))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
// javascript program to find if a given number
// is fancy or not
    function isFancy( num)
    {
     
        // To store mappings of fancy pair characters.
        // For example 6 is paired with 9 and 9 is paired with 6.
        var fp = new Map();
 
        fp.set('0', '0');
        fp.set('1', '1');
        fp.set('6', '9');
        fp.set('8', '8');
        fp.set('9', '6');
 
        // Find number of digits in given number
        var n = num.length;
 
        // Traverse from both ends,
        // and compare characters one by one
        var l = 0, r = n - 1;
        while (l <= r) {
            // If current characters at both ends
            // are not fancy pairs
            if (!fp.has(num.charAt(l)) || fp.get(num.charAt(l)) != num.charAt(r))
                return false;
            l++;
            r--;
        }
        return true;
    }
 
    // Driver Code
     
        var str = "9088806";
        if (isFancy(str))
            document.write("Yes");
        else
            document.write("No");
 
// This code contributed by aashish1995
</script>


Output

Yes







Time complexity: O(N) where N is the number of digits in the given number.
Auxiliary space: O(1), as constant space is being used.

Thanks to Gaurav Ahirwar for suggesting above solution.

Approach#2: Using a dictionary

This approach uses a dictionary to store the digits and their corresponding rotated digits. It then iterates through the digits of the given number as a string, checks if each digit has a corresponding rotated digit in the dictionary, and replaces each digit with its corresponding rotated digit in the reversed string. The resulting string is converted back to an integer and compared with the original number to determine if it is a fancy number.

Algorithm

  • Create a dictionary to store the digits and their corresponding rotated digits.
  • Convert the given number to a string and iterate through its digits.
  • Check if the current digit has a corresponding rotated digit in the dictionary. If not, return “No”.
  • Reverse the string and replace each digit with its corresponding rotated digit.
  • Convert the resulting string back to an integer and compare it with the original number.
  • If they are the same, return “Yes”. Otherwise, return “No”.

C++




#include <iostream>
#include <unordered_map>
#include <string>
 
using namespace std;
 
// Function to check if a number is fancy
string isFancy(int num) {
    // Define a map of rotated digits where each digit maps to its rotated counterpart
    unordered_map<char, char> rotatedDigits = {
        {'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}
    };
     
    // Convert the number to a string for easier manipulation
    string numStr = to_string(num);
     
    // Check each digit in the number
    for (char digit : numStr) {
        // If a digit is not in the rotatedDigits map, the number is not fancy
        if (rotatedDigits.find(digit) == rotatedDigits.end()) {
            return "No";
        }
    }
     
    // Create a string for the rotated version of the number by reversing the digits
    string rotatedStr = "";
    for (int i = numStr.length() - 1; i >= 0; i--) {
        rotatedStr += rotatedDigits[numStr[i]];
    }
     
    // If the rotated number is equal to the original number, it's fancy; otherwise, it's not
    if (stoi(rotatedStr) == num) {
        return "Yes";
    } else {
        return "No";
    }
}
 
int main() {
    int num = 96;
     
    // Call the isFancy function and print the result
    cout << isFancy(num) << endl;
     
    return 0;
}


Java




import java.util.HashMap;
 
public class FancyNumber {
    // Function to check if a number is fancy
    static String isFancy(int num)
    {
        // Define a map of rotated digits where each digit
        // maps to its rotated counterpart
        HashMap<Character, Character> rotatedDigits
            = new HashMap<>();
        rotatedDigits.put('0', '0');
        rotatedDigits.put('1', '1');
        rotatedDigits.put('6', '9');
        rotatedDigits.put('8', '8');
        rotatedDigits.put('9', '6');
 
        // Convert the number to a string for easier
        // manipulation
        String numStr = Integer.toString(num);
 
        // Check each digit in the number
        for (char digit : numStr.toCharArray()) {
            // If a digit is not in the rotatedDigits map,
            // the number is not fancy
            if (!rotatedDigits.containsKey(digit)) {
                return "No";
            }
        }
 
        // Create a string for the rotated version of the
        // number by reversing the digits
        StringBuilder rotatedStr = new StringBuilder();
        for (int i = numStr.length() - 1; i >= 0; i--) {
            rotatedStr.append(
                rotatedDigits.get(numStr.charAt(i)));
        }
 
        // If the rotated number is equal to the original
        // number, it's fancy; otherwise, it's not
        if (Integer.parseInt(rotatedStr.toString())
            == num) {
            return "Yes";
        }
        else {
            return "No";
        }
    }
 
    public static void main(String[] args)
    {
        int num = 96;
 
        // Call the isFancy function and print the result
        System.out.println(isFancy(num));
    }
}


Python3




def is_fancy(num):
    rotated_digits = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
    num_str = str(num)
    for digit in num_str:
        if digit not in rotated_digits:
            return "No"
    rotated_str = ''.join([rotated_digits[digit] for digit in num_str[::-1]])
    if int(rotated_str) == num:
        return "Yes"
    else:
        return "No"
 
num=96
print(is_fancy(num))


C#




using System;
using System.Collections.Generic;
 
public class Program {
    // Function to check if a number is fancy
    public static string IsFancy(int num)
    {
        // Define a dictionary of rotated digits where each
        // digit maps to its rotated counterpart
        Dictionary<char, char> rotatedDigits
            = new Dictionary<char, char>{ { '0', '0' },
                                          { '1', '1' },
                                          { '6', '9' },
                                          { '8', '8' },
                                          { '9', '6' } };
 
        // Convert the number to a string for easier
        // manipulation
        string numStr = num.ToString();
 
        // Check each digit in the number
        foreach(char digit in numStr)
        {
            // If a digit is not in the rotatedDigits
            // dictionary, the number is not fancy
            if (!rotatedDigits.ContainsKey(digit)) {
                return "No";
            }
        }
 
        // Create a string for the rotated version of the
        // number by reversing the digits
        string rotatedStr = "";
        for (int i = numStr.Length - 1; i >= 0; i--) {
            rotatedStr += rotatedDigits[numStr[i]];
        }
 
        // If the rotated number is equal to the original
        // number, it's fancy; otherwise, it's not
        if (int.Parse(rotatedStr) == num) {
            return "Yes";
        }
        else {
            return "No";
        }
    }
 
    public static void Main(string[] args)
    {
        int num = 96;
 
        // Call the IsFancy function and print the result
        Console.WriteLine(IsFancy(num));
    }
}


Javascript




function isFancy(num) {
  // Define a map of rotated digits
  const rotatedDigits = { '0': '0', '1': '1', '6': '9', '8': '8', '9': '6' };
 
  // Convert the number to a string
  const numStr = num.toString();
 
  // Iterate through each digit of the number
  for (const digit of numStr) {
    // Check if the digit is not in the rotated digits map
    if (!(digit in rotatedDigits)) {
      return "No"; // If any digit is not in the map, the number is not fancy
    }
  }
 
  // Reverse the number's string representation and map the digits
  const rotatedStr = numStr.split('').reverse().map(digit => rotatedDigits[digit]).join('');
 
  // Convert the rotated string back to a number
  const rotatedNum = parseInt(rotatedStr);
 
  // Check if the rotated number is equal to the original number
  if (rotatedNum === num) {
    return "Yes"; // If they are equal, the number is fancy
  } else {
    return "No"; // Otherwise, it's not fancy
  }
}
 
const num = 96;
console.log(isFancy(num)); // Output: "Yes" (96 is a fancy number)


Output

Yes








Time complexity: O(n), where n is the number of digits in the given number.
Space complexity: O(1), as the dictionary has a fixed number of elements.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads