Interview Question


Country: United States




Comment hidden because of low score. Click to expand.
0
of 0 vote

I don't understand what you mean, can you give an example?

- techinterviewquestion.com February 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

10011 should return 01101

- J@sper February 03, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@fayezelfar
J@sper is correct - 10011 should return 01101
With "01100" you've provided one's compliment.

- BenC February 06, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class TwosCompliment {
	
	public static void main(String[] args) {
		TwoC c = new TwoC();
		System.out.println(c.twosCompliment("001"));
	}
	
	private static class TwoC {
		
		public String twosCompliment(String str) {
			if(str == null || str.isEmpty()){
				return str;
			}
			char[] invertedArr = invert(str).toCharArray();
			for(int i = invertedArr.length - 1; i >= 0; i--) {
				Result result = add(invertedArr[i], '1');
				invertedArr[i] = result.result();
				if(!result.isCarry()) {
					break;
				}
			}
			return new String(invertedArr);
		}
		
		private static String invert(String str) {
			if(str == null) {
				throw new RuntimeException("Test String cannot be empty");
			}
			char[] strArray  = str.toCharArray();
			for(int i = 0; i < str.length(); i++) {
				if(strArray[i] == '1') {
					strArray[i] = '0';
				} else {
					strArray[i] = '1';
				}
			}
			return new String(strArray);
		}

		private Result add(char one, char two) {
			if(one == '1' && two == '1') {
				return new Result(true, '0');
			} else if((one == '1' && two == '0') || (one == '0' && two =='1')) {
				return new Result(false, '1');
			} else {
				return new Result(false, '0');
			}
		}
	}
	
	private static class Result {
		private boolean isCarry;
		private char result;
		
		Result(boolean isCarry, char result) {
			this.isCarry = isCarry;
			this.result = result;
					
		}
		public boolean isCarry() {
			return isCarry;
		}
		
		public char result() {
			return result;
		}
	}
}

- rangacoder February 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

string answer(string s) {
	bool flg = 0; // this determines if the first 1 from right is found. 
	for(int i = s.size() - 1; i >= 0; --i) {
		if(flg) s[i] = s[i] == '0' ? '1' : '0'; 
		else flg = s[i] == '1'; 
	}
	for(int i = 0; i < (s.size() / 2); ++i) {
		swap(s[i], s[s.size() - i - 1]); 
	}
        return s; 
}
void swap(char &a, char &b) {
	char tmp = a; 
	a = b; 	
	b = tmp; 
}

- M.Sayed February 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

not able to understand ur question can u give an example??
like what will be the answer for 001000 and how????

- sahiljulka44 February 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringOperations(){

public static void main(String[] args){
String inverseString = "111000110";
char[] array = inverseString.toCharArray();
system.out.println(String.valueOf(inverseArray(array));
system.out.println(String.valueOf(getComplement(array));

}

private static char[] inverseArray(char[] array){

//* Method 1 *//
return Collections.inverse(array);

//* Method 2 *//
char[] inverseArray;
for(int i=array.length;i>=0;i--)
{
inverseArray.add(char[i])

}

return inverseArray;
}

public getComplement(char[] array){
for(int i=array.length;i>=0;i--)
{
if(array[i]==0)
{
array[i] = 1;
}

else{
array[i]=0;
}
}
return array;
}


}

- Anonymous February 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

import java.io.*;

class StringComplement
{
static String str;
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

str = br.readLine();
String complementStr = complement(str);
System.out.println("Original String :"+str);
System.out.println("Complemented String :"+complementStr);
}
static String complement(String str)
{
// Take example : 100110
// 1 is replace with only for future reference to 1
String str1 = str.replaceAll("1","2"); //changing all 1's to 2 200220
String str2 = str1.replaceAll("0","1"); //changing all 0's to 1 211221
String str3 = str2.replaceAll("2","0"); // changing all 2's to 0 011001 //final string
return str3;

}
}

- Narendra Koli February 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

You are returning 1's complement.

- t@_@n February 04, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.*;

class StringComplement
{
static String str;
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

str = br.readLine();
String complementStr = complement(str);
System.out.println("Original String :"+str);
System.out.println("Complemented String :"+complementStr);
}
static String complement(String str)
{
// Take example : 100110
// 1 is replace with only for future reference to 1
String str1 = str.replaceAll("1","2"); //changing all 1's to 2 200220
String str2 = str1.replaceAll("0","1"); //changing all 0's to 1 211221
String str3 = str2.replaceAll("2","0"); // changing all 2's to 0 011001 //final string
return str3;

}
}

- Narendrakoli4666 February 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include<string.h>
char* mystr(char str[])
{
char temp[100];
int i,j;
for (i=strlen(str)-1,j=0;i>=0;i--,j++)
{
temp[j]=str[i];
}
printf("reverse = %s",temp);
for(i=0;i<strlen(str);i++)
{
if(str[i]=='1')
str[i]='0';
else
str[i]='1';
}
printf("1s_com= %s",str);
printf("\n");
if (str[strlen(str)-1]=='0')
str[strlen(str)-1]=str[strlen(str)-1]+1;
return str;
}
int main(void) {
// int i,j,data=5,bitpos,a,b;
char str[]="0011001";
printf("data=%s",str);
printf("2s_com=%s",mystr(str));



return 0;
}

- Shahil khan February 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include<string.h>
char* mystr(char str[])
{
char temp[100];
int i,j;
for (i=strlen(str)-1,j=0;i>=0;i--,j++)
{
temp[j]=str[i];
}
printf("reverse = %s",temp);
for(i=0;i<strlen(str);i++)
{
if(str[i]=='1')
str[i]='0';
else
str[i]='1';
}
printf("1s_com= %s",str);
printf("\n");
if (str[strlen(str)-1]=='0')
str[strlen(str)-1]=str[strlen(str)-1]+1;
return str;
}
int main(void) {
// int i,j,data=5,bitpos,a,b;
char str[]="0011001";
printf("data=%s",str);
printf("2s_com=%s",mystr(str));



return 0;
}

- shahilalam.21 February 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{
String twoComplements(String str) {
if(str == null || str.length() == 0)
return str;
StringBuilder strBuf = new StringBuilder();
for (int index = 0; index < str.length(); index++) {
if(str.charAt(index)== '0') {
strBuf.append('1');
}
else
strBuf.append('0');
}
int index = 0;
for (index = str.length() - 1; index >=0 ; index--) {
if(strBuf.charAt(index)== '0') {
strBuf.setCharAt(index,'1');
break;
}
else
strBuf.setCharAt(index,'0');
}
if(index < 0) {
strBuf.insert(0,'1');
}
return strBuf.toString();
}
}}

- EPavlova February 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. reverse the string and count the total number of characters excluding leading zeros
2. convert the reversed string to int using atoi
3. convert the result of '3' to decimal value of corresponding binary value
4. just take the negative of the number and that should work.

- aka February 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Code in Java
Time : O(n) , n=length of string
Space : O(1)

private static void twosComplement(String input){
        char[] chars=input.toCharArray();
        int consecutiveOnesCount=0;
        for(int i=chars.length-1;i>=0;i--){
            if(chars[i]=='0' && i+consecutiveOnesCount==chars.length-1){                
                consecutiveOnesCount++;
            }else if(chars[i]=='1' && i+consecutiveOnesCount!=chars.length-1){
                chars[i]='0';
            }else if(chars[i]=='0' && i+consecutiveOnesCount!=chars.length-1){
                chars[i]='1';
            }
        }
        String output=new String(chars);
        if(consecutiveOnesCount==chars.length){
            output="1"+output;
        }
        System.out.println("2's complement of input is --> "+output);
    }

- t@_@n February 08, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here the solution in c++:
1-Reverse binary number
2-Add one.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include<string>

using namespace std;


int main()
{
    char bin[]="10011";
    
    int n=(int)strlen(bin);
    
    //1-reverse number
    for(int i=0;i<n;i++)
    {
        if(bin[i]=='1')
            bin[i]='0';
        else
            bin[i]='1';
    }
    
    //2-add one to the number
    for(int i=n-1;i>=0;i--)
    {
        if(bin[i]=='0')
        {
            bin[i]='1';
            break;
        }
        else
            bin[i]='0';
    }

    cout<<"2's complement of is:"<<bin<<endl;
    
    return 0;

}

- Ed February 17, 2016 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More