int add2_recurse(int a, int b) { // recursive
// Rule: Can't use the *, /, +, =, *=, /=, +=, -= operators.
// Can use: ++ and/or --
// No loops allowed; no static local or global variables.
// What I have so far
while(b--) {
a++;
return a; }
int main() {
show_test(4, "add2", recursive);
cout << add2_recurse(4,5); cout<<" "; // correct: 9
cout<<add2_recurse(-5, 15); cout<<" "; // correct: 10
cout<<add2_recurse(20, -9); cout<<" "; // correct: 11
cout<<add2_recurse(-7, -5); cout<<" "; // correct: -12
cout<<endl;
当我运行时,&#34; 9 10 11 -12&#34;的正确输出显示时,只有11和-12显示得慢得多。关于如何让它运行得更快的任何想法?
答案 0 :(得分:2)
首先,您的解决方案有两个原因是错误的。您不使用递归,并且您正在使用循环。
至于为什么它在最后两种情况下运行得如此之慢:只要b
为负,b
一直递减到最小可能的整数,然后它会回绕到最大值可能的整数,最后它会递减直到它为0.假设一个32位整数,你将有大约40亿次迭代的循环。
您需要区分b
的负值和正值,然后根据需要递减或递增a
。
答案 1 :(得分:-1)
你不需要任何递归,在按位运算方面很容易实现加法:
#include <limits.h> /* CHAR_BIT for pedantic correctness */
int add(int a_, int b_)
{
/*
Signed types tend to have UB. Prevent this by using unsigned.
This might only work with twos-complement systems, sorry - patches welcome.
*/
const unsigned a = (unsigned)a_;
const unsigned b = (unsigned)b_;
unsigned s = 0, c = 0;
int i;
/* constant-sized loop, can be trivially unrolled if you know how many bits are in an int (e.g. 16 or 32) */
for (i = 0; i < sizeof(int) * CHAR_BIT; ++i)
{
s |= ((a ^ b ^ c) & (1 << i));
c = ((a & b) | (a & c) | (b & c)) & (1 << i);
c <<= 1;
}
return (signed)s;
}
谨防上述代码中的错误;我只是证明它是正确的,没有尝试过。