in the problem there given a positive integer num you need to convert in decimal to binary(0,1) let take num= 5 the binay convertion is 5(101) according to 8421 code we need complement of num is 010 and the integer 2 return its complement
Input:5
Output:2
Explanation: the binary representation of 5 is 101 (no leading zero bits), and its compliment is 010. So you need to output 2
Input : 18
Output: 13
Explanation: The binary representation of 18 is 10010 (no leading zero bits), and its complement is 01101. so you need to output 13
The logic is:
without using complement the 5 binary code is 101 so we need convert to binary to decimal how to get 5, so like this the complement of 5 is also understand here there is any zero in binary code the 2 pow of any value is zero.
When you understand the logic of the binary conversion of decimal to binary to improve your logical thinking by solve this problem click here to understand the logic of binary convertion
This is the code in C++:
Explanation of the code:
we need sum of all converting values so int sum=0; it is we declared in while loop we converting num to binary and also do operation where num%2 get the last value of the binary reperation so we need to 101 and by num=num/2to remove last value 10 and again the same proceess until the while loop break/false 10 as i said what we neccessary that only we do if(num%2==0) this condition only sum and i++ is not conatant it increases until the condition of while false there is more important thing is i is started with zero that why we declered int i=0; and the pow(2,i) is where the i=0 the binary of 5(101) the one is not equal to 0 so the condtion false no operation done and it reduced num=num/2; so 10 and i increases to i=1 here binary(10) so there is condtion was true operation done (2^1)*1=>2 that added to sum and the binary reduced (1) then again the condition was false so again it reduced to 0 and while condition false the sum was returned
0 Comments