Two's Complement
Find 2's complement of a number
/*
* WAP to enter a negative number in base 10 and
* find its 2's complement.
*/
import java.util.*;
class TwosComplement
{
public static void main (String args[])throws InputMismatchException
{
Scanner scan = new Scanner(System.in);
int n,i,p,b,x,carry;
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;
}
//Convert the array to store the 1s complement
for(i=0; i< x; i++){
if(a[i] == 0){
a[i] = 1;
}else{
a[i] = 0;
}
}
System.out.print("1s complement: ");
for(i=x-1; i>=0; i--){
System.out.print(a[i]);
}
//Add 1 to the last digit of 1s complement to get 2s complement
a[0] += 1;
carry = 0;
for(i=0; i < x; i++){
a[x] = a[x] + carry;
if(a[x] == 2){
a[x] = 0;
carry = 1;
}
}
System.out.print("\n2s complement: ");
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