Zoho Question | Sum of Binary-Decimal Number
Zoho Question
This is a Zoho question asked in GCE Salem 2019. Given a number, find the least binary-decimal numbers so that the sum of Binary-Decimal number is equal to the given number. Binary-Decimal numbers contains only 0, 1 ex: “100,1, 110,10,111” etc. For example, if number is 32 then output should be 11, 11, 10 because 11+11+10 = 32
Note: 10+10+10+1+1= 32 (this is also valid but contains 5 Binary-Decimal number. We should get the sum with least numbers possible so this is not the answer)
Logic
- We slice the given number accordingly until we get the sum. For example num = 32 then we separate them into 10, 10, 10. Now we have 2 remaining. Again we slice that into 1, 1.
- Now we add those 1 to 10’s ( 10+1, 10+1, 10 -> 11, 11, 10)
- If we take 1123 as an example,
- 1000 remaining 123 (have 1 hundred)
- 1000+100 remaining 23 (have 2 ten)
- 1100+10, 10 remaining 3 (have 3 one)
- 1110 +1, 10+1, 1
- 1111+11+1 = 1123
Algorithm
- We use an array to store Binary-Decimal numbers.
- Get the digit count of the given number ( Ex: num = 1123, digitcount =4)
- Use power function to find initial Binary-Decimal. (Ex: pow(10,4-1) = 1000)
- Store Binary Decimals from the first index of the array.
- Get the remaining and Decrease the Binary-Decimal(100 to 10)
- Repeat the step 4, 5 until you get the sum.
Program
#include<stdio.h> int power(int n) { int i,a=1; for(i=0;i<n;i++) { a*=10; } return a; } int main() { int temp, num; printf("Enter the number"); scanf("%d",&num); int x,n=0,BinaryDecimal,i; int arr[10] ={0}; //array to store Binary-decimal number, intially assigned zero temp = num; while(temp) //loop to find digit count { n++; temp = temp/10; } BinaryDecimal = power(n-1); //find BinaryDecimal //For example, BinaryDecimal is 100 if the digit count is 3 temp = num; while(temp) { x = temp/BinaryDecimal; //find the quotient //Ex: temp = 102, first 100, 10(condition fails), 1 for(i=0;i<x;i++) //add BinaryDecimal from start of array { arr[i] += BinaryDecimal; //add the BinaryDecimal } temp = temp % BinaryDecimal; //find the remaining BinaryDecimal = BinaryDecimal/10; //change BinaryDecimal Ex: 100 to 10 (or)10 to 1 } for(i=0;i<10;i++) { if(arr[i] != 0) printf("%d ",arr[i]); } return 0; }
You Might also like…