Manasa loves Maths

You are given an integer N. Is there a permutation of digits of integer that’s divisible by 8? A permutation of digits of integer N is defined as an integer formed by rearranging the digits of N. For example, if the number N = 123, then {123, 132, 213, 231, 312, 321} are the possible permutations.

Input Format
The first line contains an integer T i.e. number of test cases.
T lines follow, each containing the integer N.

Output Format
For each test case print YES if there exists one such re-arrangement of N such that it is divisible by 8 or NO if there isn’t.

Constraints
1 <= T <= 45
0 <= N <= 10110

Note
Re-arrangements of 10 are {10, 01} which boils down to {10, 1}.

Sample Input

2
61
75

Sample Output

YES
NO

Explanation
Test case #00: 16 is permutation of 61 which is divisible by 8.
Test case #01: None of permutation of 75, {57, 75}, are divisible by 8.

Copyright (c) 2015 HackerRank.
All Rights Reserved
Suggest Edits

Choose a translation

300 hackers have submitted code

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int val[10];
int flag = 0;
void permute(int i,int n)
    {
    int j,k,t;
    long int N;
    if(i == n)
    {
       N=0;
       for(k=0;k<=n;k++)
           N = N*10 + val[k];
       N = N % 1000;
       if(flag == 0)
           {
           if(N%8 == 0)
               flag =1;
       }
       //printf("%ld\n",N);
    }
    else
        {
        for(j=i;j<=n;j++)
        {
        t=val[i];
        val[i]= val[j];
        val[j] = t;
           permute(i+1,n);
        t=val[i];
        val[i]= val[j];
        val[j] = t; 
        }
    }
}
int main() {
    int T;
    char ch[115];
    int arr[10]={0},i,j;
    long long int N;
    scanf("%d",&T); 
    while(T--)
        {
        N=0;
        for(i=0;i<10;i++)
            arr[i]=0;
        scanf("%s",ch);
        //printf("%s\n",ch);
        //continue;
        for(i=0;i<strlen(ch);i++)
            {
            arr[ch[i]-48]=1;
        }
        j=0;
        for(i=0;i<10;i++)
            {
            //printf("%d ",arr[i]);
            if(arr[i] == 1)
              val[j++] = i; //N = N*10 + i;
        }
        //for(i=0;i<j;i++)
          //printf("%d ",val[i]);
       // break;
        flag = 0;
        //printf("%d\n",flag);
        permute(0,j-1);
        //printf("%d\n",flag);
        if(flag == 1)
            printf("YES\n");
        else
            printf("NO\n");
        //if(arr[0] == 1)
           // N = N*10;        
        //printf(" %lld\n",N);
        //break;    
    }
    return 0;
}

Compile & Run : http://ideone.com/trpXu6
Follow On Twitter : https://twitter.com/codeifucansolve
Follow on Quora : http://codeifyoucansolve.quora.com/Manasa-loves-Maths