Amazon Interview Question
Country: India
isn't two compliement of a negative number is the postive number itself.
int main()
{
int x=-1;
printf("%x\n", x);
printf("%x\n", ~x+1);
}
2's complement of a negative number is simply a positive magnitude of that number. For example, if number is -6 its 2's complement will be 6.
I think this is the code
#include <stdio.h>
main() {
int a=-6;
a = (~a)+1;
printf("%d\n",a);
}
public class TwosComplement {
public static void main(String[] args) {
int no = -8;
printBits(no);
printBits(~no);
printBits(~no + 1);
}
public static void printBits(int no) {
System.out.println("\nBinary format of:" + no + "\n"
+ Integer.toBinaryString(no));
for (int i = 31; i >= 0; i--)
System.out.print((((no & (1 << i)) >>> i) > 0) ? "1" : "0");
}
}
I would suggest that there be more clarity on the input. One possible cpp solution.
#include<iostream>
#include<stdlib.h>
#include<cstring>
using namespace std;
//assumptions:
//1. input is a binary number in a char string
int main(void)
{
string str;
cin >> str;
//flip the digits
cout << str << endl;
for (int i=0;i<str.size();i++)
str[i] = ((str[i] == '0') ? '1' : '0');
cout << str <<endl;
for(int i = str.size();i>=0;i--)
if (str[i] == '0')
{
str[i] = '1';
break;
}
else
{
str[i] = '0';
continue;
}
cout << str <<endl;
return 0;
}
@Nascent
- Murali Mohan July 02, 2013Do we need to compute the two's compliment form and print it out as a string? Otherwise, since a computer anyway stores a number in two's compliment form, we can just print out the bits of the memory word.