简体   繁体   中英

Recursive binary to decimal function without pow() or loops

I am doing a C course. I need to do a recursive XOR binary but I have some limitations. I can't use loop or any math.h functions, nor can I call another function from the XOR function.

This is the function prototype:

int binaryXor(int firstnumber[], int secondnumber[], int length);

where firstnumber and secondnumber are arrays with the same length of 1s and 0s and length is their length.

The function should return the decimal value of the XOR of those two arrays. Doing the XOR is quite simple, but how can I convert it to decimal with all the limitations?

In order to write a recursive function, with no loops, you need to answer the following question:

"How can I express the answer to my problem in terms of a smaller problem?"

In this case, the problem is that you have length digits to look at, but you're not allowed to loop. So, how do you express an xor of size length in terms of a smaller xor, together with some amount of work that doesn't require a loop?

[Edit: hang on, just looked at your question again, and you say you already have the xor sorted, so I guess you've already done this. In that case my comment above is the only thing you need to know: you're finished. An int in C is not a decimal value, it's just a value. You don't need to convert anything to decimal in order to store or return it in an int .

If you're interested though, I can post code that does convert an int to a decimal value using a recursive function. One simple way is to work out on the way "down" how many digits are required, by comparing with bigger and bigger powers of 10, and then on the way back "up" print the digits out starting from the end.]

This is a standard recursive question. The trick is to realize that the integer value of aa string of 1s and 0s followed by a 1 or 0, is 2 * the integer value of the string plus the value of the digit.

So you will want to do something like

if( length <= 0) return 0;

return 2 * binaryXOR(firstnumber, secondnumber, length - 1) + (firstnumber[length - 1] ^ secondnumber[length - 1]);

可以使用递归函数调用来代替循环。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM