题目链接:http://ac.jobdu.com/problem.php?pid=1507
分析:题目要求不能用+、-、*、/实现两个数的加法,此时就应该考虑到位运算。两个数的“异或”是这两个数不带进位的和,而两个数的”与“的结果是这两个数相加时需要进位的位,将该位不断左移,目的是找到其最终应该待的位置。
1. 求出两个数的异或和与的结果;
2. 将与的结果左移一位;
3. 再将异或的结果与左移后的结果求“异或”和“与”,反复;
4. 直到与的结果为0。表示进位的位已经找到其待的位置。结束。
C++实现:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
void process(int x,int y)
{
int sum = 0;
int carry = 0;
do {
sum = x ^ y;
carry = ( x & y ) << 1;
x = sum;
y = carry;
}while(carry != 0);
printf("%d\n", sum);
}
void input()
{
int x, y;
stack<int> s1, s2;
while(scanf("%d %d", &x, &y) != EOF)
{
process(x, y);
}
}
int main()
{
input();
return 0;
}