24th Nov 2020, 4:52 PM
Ankit Sharma
Ankit Sharma - avatar
11 Respostas
+ 4
Your code is incomplete, it was truncated because it exceeds character limits. You should save your code in SoloLearn and share the saved code link instead of raw text code like this. Follow this guide to sharing links 👇 https://www.sololearn.com/post/75089/?ref=app
24th Nov 2020, 5:01 PM
Ipang
+ 2
Ankit Sharma Thanks for uploading the code 👍 Can you describe me the program purpose? possibly some examples of inputs and expected output. I need that to test the code.
24th Nov 2020, 5:10 PM
Ipang
+ 2
It's a programme to add binary numbers Input two binary numbers And get their sum as output E.g. Input 1 1 Output 10
24th Nov 2020, 5:11 PM
Ankit Sharma
Ankit Sharma - avatar
+ 2
Ok I'll take a look at it I'll be back a while later ...
24th Nov 2020, 5:21 PM
Ipang
+ 2
Ankit Sharma Martin Taylor had shown you the C++ way of handling binary numbers using std::bitset. I was thinking you were doing what you did for a school tssk hence the self-written code. Where the use of std::bitset was allowed for the task, then you may get yourself acquainted to it here 👇 http://www.cplusplus.com/reference/bitset/bitset/
24th Nov 2020, 10:02 PM
Ipang
+ 2
I have to do it via functions and function should also call other function in itself like here ans function calls reverse. I have to do it without arrays.
25th Nov 2020, 2:58 AM
Ankit Sharma
Ankit Sharma - avatar
+ 2
The array is used to simplify the code, without the array we'd have to write the bit accumulation part twice, once for <n1> and once more for <n2>. Here I separate the bit accumulation part into another function named `bin_to_dec`, the function is called by `addBinary` function passing <n1> and <n2>. int bin_to_dec(int n) { int result = 0, bit = 1; while(n) { int digit = n % 10; if(digit == 1) result += bit; bit <<= 1; n /= 10; } return result; } int addBinary(int n1, int n2) { return bin_to_dec(n1) + bin_to_dec(n2); } Considering the limit of `int` type, it is also worth noting that input will be limited to 10 digits only.
25th Nov 2020, 5:57 AM
Ipang
24th Nov 2020, 5:05 PM
Ankit Sharma
Ankit Sharma - avatar
+ 1
Ankit Sharma I haven't figured out your problem yet, but I came out with a shorter version of the function. I think I may need more time to fully check your function for the problem, maybe someone else here can help sooner though. If you want, you can see my implementation, it goes like this int addBinary(int n1, int n2) { int array[2] = {n1, n2}; int result = 0; for(int i = 0, bit, digit, temp; i < 2; i++) { temp = 0; bit = 1; while(array[i]) { digit = array[i] % 10; if(digit == 1) { temp += bit; } bit <<= 1; array[i] /= 10; } result += temp; } return result; }
24th Nov 2020, 6:02 PM
Ipang