30 Day Risk-Free Guarantee:
100% money back if you're unsatisfied.
Book (308 Pages):
  • 150 Programming Interview Questions and Solutions
  • Five Proven Approaches to Solving Tough Algorithm Questions
  • Ten Mistakes Candidates Make -- And How to Avoid Them
  • Steps to Prepare for Behavioral and Technical Questions
  • Interview War Stories: A View from the Interviewer's Side
  • Book Preview and More Info

Video (One Hour):
  • Watch CareerCup's founder perform a totally unscripted technical interview of a candidate.
  • Overview of what interviewers look for in software engineering jobs.
  • Technical questions with white-boarding coding where the candidate does well - and struggles.
  • Interviewer reviews with what went well and poorly.
  • Video Preview and More Info

Resume Review (24 - 48hr)
  • Get your resume reviewed by a trained engineering interviewer. More Info
All Products / Services


Express Prep Package (Book)
$29.99 for e-book | $32.45 for paperback
Buy E-Book Buy on Amazon


Standard Prep Package (E-Book & Video)
Emailed Instantly | $39.99
Buy Standard

Elite Prep Package (E-Book, Video & Resume)
Emailed Instantly | $99.99
Buy Elite
 



Write a function to add two numbers, without using any arithmetic operator. Even the ++ in for statement is not allowed

30


Anonymous on July 27, 2008 |Edit | Edit

The following code in python will do.
If it has to be coded in c++, the for loop can use shifting as well.

add2(a, b, n) is a function to add n-bit numbers a and b.

##################
import sys

def lsb(n):
return n & 1

def add2(a, b, n):
s = 0
c = 0

for i in range(n):
lsba = lsb(a)
lsbb = lsb(b)
lsbc = lsb(c)

s += (lsba ^ lsbb ^ lsbc) << i
c = lsba & lsbb | lsbb & lsbc | lsbc & lsba

a >>= 1
b >>= 1

return s

if __name__ == "__main__":
print add2(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]))

python on August 03, 2008 |Edit | Edit

unfortunately with python .. you need to atleast do proper indentation, else its really confusing to find out where the loop ends. (this code above has lost its indentation) and hence totally unreadable. (maybe you can put comments to indicate where the loops start and end)

yippie .. captcha is out :-)

Anonymous on August 05, 2008 |Edit | Edit

Added some comments and fixed an error (used '|' instead of '+'). It's simply emulating a binary adder.

##################
import sys

# function to extract LSB
def lsb(n):
return n & 1

# function to add 2 n-bit numbers a & b
def add2(a, b, n):
# intialize sum and carry
s = 0
c = 0

# for loop begins
for i in range(n):
lsba = lsb(a)
lsbb = lsb(b)
lsbc = lsb(c)

s |= (lsba ^ lsbb ^ lsbc) << i
c = lsba & lsbb | lsbb & lsbc | lsbc & lsba

a >>= 1
b >>= 1

# for loop ends

return s

if __name__ == "__main__":
print add2(int(sys.argv[1]), int(sys.argv[2]),
int(sys.argv[3]))

Kapil Goel on August 07, 2008 |Edit | Edit

Piece of code in java that serve this functionality is
public class Test1 {

public static void main(String[] args) {
System.out.println((new Test1()).addNumbers(8888, 1976543));
}

/**
* write an function to add two numbers, without using any arithmetic
* operator. Even the ++ in for statement is not allowed.
*/
public int addNumbers(int a, int b) {
String result = "";
String num1 = Integer.toBinaryString(a);
String num2 = Integer.toBinaryString(b);

boolean carry = false;
String res = "";
if (num1.length() == num2.length()) {
for (int i = num1.length() - 1; i >= 0; i--) {
res = addBinaryNumber(num1.charAt(i), num2.charAt(i));
if (carry) {
if (res.charAt(0) == '0')
carry = false;
res = addBinaryNumber(res.charAt(1), '1');
}
if (res.charAt(0) == '1')
carry = true;
result += res.charAt(1);
}
if (carry)
result += '1';
}
else if (num1.length() < num2.length()) {
for (int i = num1.length() - 1; i >= 0; i--) {
res = addBinaryNumber(num1.charAt(i), num2.charAt(i + num2.length() - num1.length()));
if (carry) {
if (res.charAt(0) == '0')
carry = false;
res = addBinaryNumber(res.charAt(1), '1');
}
if (res.charAt(0) == '1')
carry = true;
result += res.charAt(1);
}
for (int i = num2.length() - num1.length() - 1; i >= 0; i--) {
if (carry) {
res = addBinaryNumber(num2.charAt(i), '1');
carry = false;
if (res.charAt(0) == '1')
carry = true;
result += res.charAt(1);
}
else
result += num2.charAt(i);
}
if (carry)
result += '1';
}
else {
for (int i = num2.length() - 1; i >= 0; i--) {
res = addBinaryNumber(num2.charAt(i), num1.charAt(i + num1.length() - num2.length()));
if (carry) {
if (res.charAt(0) == '0')
carry = false;
res = addBinaryNumber(res.charAt(1), '1');
}
if (res.charAt(0) == '1')
carry = true;
result += res.charAt(1);
}
for (int i = num1.length() - num2.length() - 1; i >= 0; i--) {
if (carry) {
res = addBinaryNumber(num1.charAt(i), '1');
carry = false;
if (res.charAt(0) == '1')
carry = true;
result += res.charAt(1);
}
else
result += num1.charAt(i);
}
if (carry)
result += '1';
}
return BinaryToInt(reverse(result));
}

private String addBinaryNumber(char a, char b) {
String result = "";
if (a == '0' && b == '0')
result = "00";
if (a == '0' && b == '1')
result = "01";
if (a == '1' && b == '0')
result = "01";
if (a == '1' && b == '1')
result = "10";
return result;
}

private String reverse(String arg) {
String reverseString = "";
for (int i = arg.length() - 1; i >= 0; i--) {
reverseString += arg.charAt(i);
}
return reverseString;
}

private int BinaryToInt(String num) {
int result = 0;
for (int i = 0; i < num.length(); i++) {
if (num.charAt(i) == '1')
result += Math.pow(2, num.length() - i - 1);
}
return result;
}
}

Kapil Goel on August 07, 2008 |Edit | Edit

public class Test1 {

public static void main(String[] args) {
System.out.println((new Test1()).addNumbers(8888, 1976543));
}

/**
* write an function to add two numbers, without using any arithmetic
* operator. Even the ++ in for statement is not allowed.
*/
public int addNumbers(int a, int b) {
String result = "";
String num1 = Integer.toBinaryString(a);
String num2 = Integer.toBinaryString(b);

boolean carry = false;
String res = "";
if (num1.length() == num2.length()) {
for (int i = num1.length() - 1; i >= 0; i--) {
res = addBinaryNumber(num1.charAt(i), num2.charAt(i));
if (carry) {
if (res.charAt(0) == '0')
carry = false;
res = addBinaryNumber(res.charAt(1), '1');
}
if (res.charAt(0) == '1')
carry = true;
result += res.charAt(1);
}
if (carry)
result += '1';
}
else if (num1.length() < num2.length()) {
for (int i = num1.length() - 1; i >= 0; i--) {
res = addBinaryNumber(num1.charAt(i), num2.charAt(i + num2.length() - num1.length()));
if (carry) {
if (res.charAt(0) == '0')
carry = false;
res = addBinaryNumber(res.charAt(1), '1');
}
if (res.charAt(0) == '1')
carry = true;
result += res.charAt(1);
}
for (int i = num2.length() - num1.length() - 1; i >= 0; i--) {
if (carry) {
res = addBinaryNumber(num2.charAt(i), '1');
carry = false;
if (res.charAt(0) == '1')
carry = true;
result += res.charAt(1);
}
else
result += num2.charAt(i);
}
if (carry)
result += '1';
}
else {
for (int i = num2.length() - 1; i >= 0; i--) {
res = addBinaryNumber(num2.charAt(i), num1.charAt(i + num1.length() - num2.length()));
if (carry) {
if (res.charAt(0) == '0')
carry = false;
res = addBinaryNumber(res.charAt(1), '1');
}
if (res.charAt(0) == '1')
carry = true;
result += res.charAt(1);
}
for (int i = num1.length() - num2.length() - 1; i >= 0; i--) {
if (carry) {
res = addBinaryNumber(num1.charAt(i), '1');
carry = false;
if (res.charAt(0) == '1')
carry = true;
result += res.charAt(1);
}
else
result += num1.charAt(i);
}
if (carry)
result += '1';
}
return BinaryToInt(reverse(result));
}

private String addBinaryNumber(char a, char b) {
String result = "";
if (a == '0' && b == '0')
result = "00";
if (a == '0' && b == '1')
result = "01";
if (a == '1' && b == '0')
result = "01";
if (a == '1' && b == '1')
result = "10";
return result;
}

private String reverse(String arg) {
String reverseString = "";
for (int i = arg.length() - 1; i >= 0; i--) {
reverseString += arg.charAt(i);
}
return reverseString;
}

private int BinaryToInt(String num) {
int result = 0;
for (int i = 0; i < num.length(); i++) {
if (num.charAt(i) == '1')
result += Math.pow(2, num.length() - i - 1);
}
return result;
}
}

Rohith Menon on August 11, 2008 |Edit | Edit

int main(int argc, char *argv[])
{
if (argc != 3) {
cerr << "Enter a,b" << endl;
return 1;
}

int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = (a&b) << 1;
int sum = a^b;
while (c != 0) {
int tmp_sum = sum;
sum ^= c;
c = c & tmp_sum;
c <<= 1;
}

cout << "a+b = " << sum << endl;
return 0;
}

neoreaves on August 19, 2008 |Edit | Edit

i think the while loop is not needed as it always happens once. we just need to xor with the carry
while (c != 0) {
int tmp_sum = sum;
sum ^= c;
c = c & tmp_sum;
c <<= 1;
}
replaced by
sum ^=c;

Anonymous on March 02, 2009 |Edit | Edit

I think Rohan's answer is correct. If there is no while then it wont work when there is more than one carry.

Anonymous on March 02, 2009 |Edit | Edit

Sorry i mean Rohith Menon's anwer is correct!

Anonymous on November 23, 2009 |Edit | Edit

looks like ROhith used Booth's algorithm

Anonymous on September 01, 2008 |Edit | Edit

Here is the recursive call. I am trying to figure out wat exactly it means. anyone ????

#include<stdio.h>
#include<conio.h>

int add(int a, int b){
printf("%d %d\n",a,b);
if (!a) return b;
else
return add((a & b) << 1, a ^ b);
}

int main(){
printf("Enter the two numbers: \n");
int a,b;
scanf("%d",&a);
scanf("%d",&b);
printf("Sum is: %d %d",add(a,b));
getch();
}

Rats on April 14, 2009 |Edit | Edit

hi can u plz explain why do we need to shift the sum i.e. in this case
(a & b) << 1

codemonk on August 27, 2009 |Edit | Edit

but the question is... "add two nos without using any ARITHMETIC OPERATORS"... so sorry to say but ur solution wont work here.

Anonymous on September 01, 2008 |Edit | Edit

Here is the recursive call. I am trying to figure out wat exactly it means. anyone ????

#include<stdio.h>
#include<conio.h>

int add(int a, int b){
printf("%d %d\n",a,b);
if (!a) return b;
else
return add((a & b) << 1, a ^ b);
}

int main(){
printf("Enter the two numbers: \n");
int a,b;
scanf("%d",&a);
scanf("%d",&b);
printf("Sum is: %d %d",add(a,b));
getch();
}

asdf on September 02, 2008 |Edit | Edit

i think last two solutions are the same except that the previous one is recursive!

tilo1583 on September 19, 2008 |Edit | Edit

@neoreaves

can u tell what your intuition was behind this solution

Vishesh Garg on November 03, 2008 |Edit | Edit

@neoreaves
I think what u proposed is incorrect.
Take the example of 001 & 111

Step 1: a&b and a^b
001 001
&111 ^111
----- -----
001 110
(c) (sum)

Step2: c<< 010

Step3:sum^c
110
^010
-----
100 (incorrect-should be 1000)

Actually,the sequential XORing of c can pop up new carrys which have to be taken care of.

dilip on December 18, 2008 |Edit | Edit

u've missed the last 2 steps here.
u have the new sum as 100 and carry also as 100 (110&010 << 1) . Now the xor (sum part) of these two is 000, while the carry is 100 & 100 << 1 which is 1000. Now the new sum is 0000 ^ 1000 which is 1000 and carry is 0000 & 1000 which is 0 and now we return the sum which is 1000!

gJ on November 14, 2008 |Edit | Edit

Rohit Menon,
Could you explain how you came up with ur solution ?

Thanks.

D on January 23, 2009 |Edit | Edit

Answer is very simple if both numbers are positive.

Lets say 2 numbers are A and B. where A is the bigger number and B is smaller number

To achieve A+B we can do this

A+B = A*2 - (A - B)

This works because A*2 essentially is A+A and then we subtract the extra that we added by sutracting the difference between A and B.

Daniel Johnson on February 01, 2009 |Edit | Edit

With few more if statements, this can also be made to work for B > A and also if A and B are negative.

sv on January 29, 2009 |Edit | Edit

Here is recursive and non recursive answer:
// Add 2 unsigned digit without using arithmetic operator
public uint Add2DigitWithoutArithmeticOperator(uint i, uint j)
{
uint c = i & j;
while (c != 0)
{
i = i ^ j;
j = c << 1;
c = i & j;
}
return i ^ j;
}

public uint Add2DigitWithoutArithmeticOperatorRecursive(uint i, uint j)
{
uint c = i & j;
if (c == 0)
{
return i ^ j;
}
else
{
Add2DigitWithoutArithmeticOperatorRecursive(i ^ j, c << 1);
}
}

Daniel Johnson on February 01, 2009 |Edit | Edit

Can somebody first explain the algorithm and then code. Just writing code doesn't always help others.

Documenting your code within these triple brackets can preserve whitespace, which nobody seem to use.

Adish Jain on February 18, 2009 |Edit | Edit

int a = 100; int b = 200;
char* c = (char*)a;
printf("%d\n",(int)&c[b]);

Anonymous on February 26, 2009 |Edit | Edit

i think the simple answer would be a-(-b)

ABC123 on May 03, 2009 |Edit | Edit

Can anybody pls explain how @rohan or @sv solution works ... Please give some hints so that we can start ....

codemonk on August 27, 2009 |Edit | Edit

hey just trace the code by taking some easy example (say add 2 and 3).

LOLer on August 20, 2009 |Edit | Edit

ABC123 : _NULL_ that's what you gathered from this thread, shame on you. read the solution of others posted earlier. so many solutions are there you can't understand even one. then you should not be coming to this site to view questions.

Anonymous on September 05, 2009 |Edit | Edit

the code with explanation ....

simple xoring gives us the sum but it will not handle carry . so we and first and then xor , at any instant if carry becomes 0 we stop and output .

int temp,sum,carry;

carry= (a&b)<<1;
sum=a^b;

while(carry!=0)
{
t=sum;
sum=sum^carry;
carry=carry^t;
carry<<=1;

}

Anonymous on June 19, 2010 |Edit | Edit

scanf("%d%d",&a,&b);
printf("%d",printf("%*s%*s",a," ",b," "));

Add a Text Comment | Add Runnable Code
Name:
Comment:

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








Amazon (1033)Bloomberg LP (403)Qualcomm (117)Adobe (88)Goldman Sachs (78)NetApp (49)IBM (43)Morgan Stanley (33)CapitalIQ (30)Sophos (25)Achieve Internet (23)Electronic Arts (19)Motorola (18)Research In Motion (17)Flipkart (16)
Microsoft (867)Google (141)NVIDIA (98)Yahoo (82)Epic Systems (69)Expedia (47)VMWare Inc (43)Apple (32)Cisco Systems (28)Facebook (23)Infosys (22)Agilent Technologies (19)Sage Software (17)Deshaw Inc (16)FlexTrade (15)
More Companies »
Software Engineer / Dev... (1062)Financial Software Deve... (170)Testing / Quality Assur... (56)Analyst (35)Virus Researcher (25)Field Sales (15)Developer Program Engin... (9)Front-end Software Engi... (6)MyJoB (5)area sales manager (4)Assistant (3)Cabin crew (2)Accountant (1)personnel (1)Intern (1)
Software Engineer in Te... (288)Program Manager (65)Development Support Eng... (47)INTERN(MSIDC) (28)Web Developer (18)System Administrator (10)Consultant (10)Production Engineer (5)Associate Technology L2 (5)AcquireKnowledge (4)Product Security Engine... (3)Solutions Architect (2)Gamer (1)mts (1)Fresh graduate interview (0)
More Job Titles »
Algorithm (1073)Terminology & Trivia (294)C (166)Object Oriented Design (159)Java (121)Testing (114)Arrays (101)Operating System (78)Database (70)Linked List (62)String Manipulation (56)Networking / Web / Inte... (44)Threads (36)Linux Kernel (33)PHP (22)
Coding (511)C++ (204)Behavioral (159)Data Structures (155)Experience (116)Brain Teasers (111)Computer Architecture &... (79)General Questions and C... (73)Trees and Graphs (69)Math & Computation (57)Application / UI Design (45)Ideas (38)System Design (35)Puzzles (30)Bit Manipulation (20)
More Topics »
CareerCup Official Interview Book Daily Questions Requests for Help Mock Interviews Video for Cracking the Coding Interview Job Placement Service CareerCup Blog
My Profile Edit Profile & Email Settings Sign Out