題目描述:
寫一個函數,求兩個整數之和,要求在函數體內不得使用+、-、*、/四則運算子號。
輸入:
輸入可能包含多個測試範例。
對於每個測試案例,輸入為兩個整數m和n(1<=m,n<=1000000)。
輸出:
對應每個測試案例,輸出m+n的值。
範例輸入:
3 47 9
範例輸出:
716
解法一:
利用位元運算(^,&)類比加法:(參考劍指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];}
真是靈活。