Math, asked by rishilaugh, 1 year ago

given a string of digits as input you have to return the greatest number divisible by 3 formed using the digits, as a string.

Answers

Answered by kvnmurty
0

// given a string of digits, find greatest number divisible by 3
#include <stdio.h>
#define SIZE 100;

int CheckDivisible(char *num); //chk divisibility by 3
long int sortDigits(char * num); //sort in descending order. return value

main()
{
   char number[100]; int n, i; char newNumber[100];

      printf("Number: ");
      scanf("%s",number);
       
      if (! CheckDivisible(number)) {
           printf("\nGiven number not divisible by 3");
           return;
      }
      n = sortDigits(number, newNumber);
      printf("Greatest number divisible by 3 formed using digits in %s is: %ld\n",number, n);
     // newNumber contains the string of digits of  n
}

int checkDivisibile(char *num)  // by 3
 {  
   int k, sum;

      for (sum=0; *num ; num++) 
          sum += *num;
      if (sum % 3) return (0);
      else return(1);
}

long int sortDigits(char *num, char *newNum)

              // in descending order & return value
{
    // simple sorting 
    int m, n, k; long int N=0;


       for (m = 0; m < strlen(num); m++) {
           for (n=m+1; num[n] ; n++) {
               if (num[n] > num[m]) {
                   int z = num[m]; num[m] = num[n]; num[n] = z;
               }
           }
           N = N * 10 + num[m];

           newNum[k++] = '0' + num[m] ; 
       }

       newNum[k]= '\0';
       return N;


}

 


perfectbrainly: thanks a lot
Similar questions