Adobe Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
Hey Deadlock, wher did yu give the written .. Bglr/Noida n the opening is for Noida, uhh ..??
//Given a binary number in string form, write a function to return its two's complement in string form.
#include<stdio.h>
#include<string.h>
void two_compl(char *s)
{
int i = strlen(s) - 1;
while(s[i] == '0')
{
i--;
}
i--;
while(i >= 0)
{
if(s[i]=='0')
s[i] = '1';
else
s[i] = '0';
i--;
}
printf("%s",s);
}
int main()
{
char s[] = "1101";
two_compl(s);
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "001101";
char [] charr = s1.toCharArray();
boolean firstSigBitFound = false;
for(int i=(charr.length-1);i>=0;i--){
if(charr[i]=='1' && !firstSigBitFound){
firstSigBitFound=true;
}else if(firstSigBitFound){
if(charr[i]=='1'){
charr[i] = '0';
}else{
charr[i] = '1';
}
}
}
}
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char a[5]="1010";
int i,len=strlen(a);
for(i=0;i<len;i++){
if(a[i]=='0')
a[i]='1';
else
a[i]='0';
}
printf("1's complement=%s\n",a);
for(i=len-1;i>=0;i--){
if(a[i]=='1')
a[i]='0';
else if(a[i]=='0'){
a[i]='1';
printf("2's complement is=%s",a);
break;
}
}
if(i==-1){
printf("2's complement is=");
printf("1");
puts(a);
}
}
For 2’s complement, we first find one’s complement. We traverse the one’s complement starting from LSB (least significant bit), and look for 0. We flip all 1’s (change to 0) until we find a 0. Finally, we flip the found 0. For example, 2’s complement of “01000” is “11000” (Note that we first find one’s complement of 01000 as 10111). If there are all 1’s (in one’s complement), we add an extra 1 in the string. For example, 2’s complement of “000” is “1000” (1’s complement of “000” is “111”).
Ya that fine kamal. But there is one more method which is implemented up.. You need to start from left hand side i.i LSB and till 1 comes for the first time you just copy the same bits at the same location. Then after the 1, just flip the bits. This will give 2's coplement of a number.
- pd April 16, 2012E.g. 001100 --> 110100