Algorithm to find sum of integers
Date: Oct 2014
Level: Basic


INTERVIEW QUESTIONS

Company: Apple
Question Title: Algorithm to find sum of integers
Language: C++
QUESTION DETAILS:

Write code to sum two integers without using a+b method; you have to use either ++ or --
How you will handle negative numbers?


Following is the logic used:
#include <iostream>
using namespace std;
int add( int x, int y)
{
// both x and y are positive
if( x>=0 && y>=0){
while(x){
++y;
--x;
}
cout<<y;
}
// x positive and y negative
else if( x>=0 && y<=0){
while(x){
++y;
--x;
}
cout<<y;
}
//y positive and x negative
else if( x<=0 && y>=0 ){
while(x){
++x;
--y;
}
cout<<y;
}
// both negative
else{
while(x){
--y;
++x;
}
cout<<y;
}
}

int main()
{
add(17,-1);
return 0;
}
All Questions