Number Complement The complement of a number is defined here as the number\'s bi
ID: 3841664 • Letter: N
Question
Number Complement The complement of a number is defined here as the number's bitwise inversion from its highest-order 1-bit through its lowest-order bit. For example, the number n 5 is represented as 00000101 in binary. The binary complement of n is 010, which is 2 in decimal notation. Complete the getlntegerComplement function in your editor. It has has one parameter: a base-10 integer, n. This function must return the complement of n as a base-10 integer Input Format Locked stub code in the editor reads a single integer, n from stdin and passes it to the function Constraints o s n s 105 Output Format Return an integer denoting the complement of n. Sample Input 0 50 Sample output 0 13 Explanation 0Explanation / Answer
Solution.java
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
//Scanner object is used to get the inputs entered by the user
Scanner in=new Scanner(System.in);
//Declaring variables
int res;
int _n;
/* This while loop continues to execute
* until the user enters a valid number
*/
while(true)
{
//Getting the number entered by the user
System.out.print("Enter a number :");
_n=in.nextInt();
if(_n <0 || _n>100000)
{
System.out.println("** Invalid.Must be between 0-100000 **");
continue;
}
else
{
break;
}
}
//Calling the method by passing the user entered number as argument
res=getIntegerComplement(_n);
//Displaying the output
System.out.println("Output :"+res);
}
/* This method will convert the decimal to binary form
* and find the complement of that binary form
* and later convert it into decimal format
*/
private static int getIntegerComplement(int _n) {
int bNum[]=new int[30];
int i=0;
int dNum=0;
while(_n>0)
{
bNum[i++]=_n%2;
_n=_n/2;
}
for(int k=0;k<i;k++)
{
if(bNum[k]==0)
{
bNum[k]=1;
}
else if(bNum[k]==1)
{
bNum[k]=0;
}
}
for(int k=0;k<i;k++)
{
dNum+=bNum[k]*Math.pow(2,k);
}
return dNum;
}
}
_______________________
Output:
Enter a number :100
Output :27
_______________________
Output#2:
Enter a number :50
Output :13
____________Plz.Could you rate me well .Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.