-
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
-
输入可能包含多个测试样例。
对于每个测试案例,输入为两个整数m和n(1<=m,n<=1000000)。 -
对应每个测试案例,输出m+n的值。
-
3 4 7 9
-
7 16
-
题目描述:
-
输入:
-
输出:
-
样例输入:
-
样例输出:
利用位运算(^,&)模拟加法:(参考剑指OFFER:http://zhedahht.blog.163.com/blog/static/254111742011125100605/)
#include<stdio.h>
int main() {
int a, b, sum, carry;
while(scanf("%d %d", &a, &b) != EOF) {
while(b) {
sum = a^b;
carry = a&b;
a = sum;
b = carry;
b <<= 1;
}
printf("%d\n", sum);
}
return 0;
}
/**************************************************************
Problem: 1507
User: wusuopuBUPT
Language: C
Result: Accepted
Time:10 ms
Memory:912 kb
****************************************************************/
方法二(很狡猾的方法,参考剑指OFFER下面的回复http://zhedahht.blog.163.com/blog/static/254111742011125100605/):
我们知道,指针和一维数组有如下关系:c[b] == *(c+b*sizeof(b))
那么&c[b] == (c+b*sizeof(b))
如果sizeof(b) == 1,那么就有&c[b] == (c+b)啦。
所以,可以这样实现:
int add(int a,int b){
char * c;
c = (char *) a;
return &c[b];
}
真是灵活!