One's Complement
Find 1's complement of a number
/*
* WAP to enter a negative number in base 10 and find
* its 1's complement.
*/
import java.util.*;
class OnesComplement
{
public static void main (String args[])throws InputMismatchException
{
Scanner scan = new Scanner(System.in);
int n,i,p,b,x;
System.out.println("Enter a number (in base 10): ");
n = scan.nextInt();
if(n< 0){
int a[] = new int[100];
p = -1*n;
x=0;
//Convert the number to binary
while(p>0){
b = p%2;
a[x++] = b;
p=p/2;
}
for(i=0; i< x; i++){
if(a[i] == 0){
a[i] = 1;
}else{
a[i] = 0;
}
}
for(i=x-1; i>=0; i--){
System.out.print(a[i]);
}
}else{
System.out.println("Invalid number. Please enter a negative number.");
}
}//end of main
}//end of class
Have something to say? Log in to comment on this post.
0 comments