Check if a given number is Fancy

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


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 C++ implementation of above idea.

// C++ program to find if a given number is fancy or not.
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;
    return true;

// Driver program
int main()
    string str = "9088806";
    isFancy(str)? cout << "Yes": cout << "No";
    return 0;



Thanks to Gaurav Ahirwar for suggesting above solution.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Writing code in comment? Please use, generate link and share the link here.