当前位置:   article > 正文

C语言 | Leetcode C语言题解之第67题二进制求和

C语言 | Leetcode C语言题解之第67题二进制求和

题目:

题解:

  1. void reserve(char* s) {
  2. int len = strlen(s);
  3. for (int i = 0; i < len / 2; i++) {
  4. char t = s[i];
  5. s[i] = s[len - i - 1], s[len - i - 1] = t;
  6. }
  7. }
  8. char* addBinary(char* a, char* b) {
  9. reserve(a);
  10. reserve(b);
  11. int len_a = strlen(a), len_b = strlen(b);
  12. int n = fmax(len_a, len_b), carry = 0, len = 0;
  13. char* ans = (char*)malloc(sizeof(char) * (n + 2));
  14. for (int i = 0; i < n; ++i) {
  15. carry += i < len_a ? (a[i] == '1') : 0;
  16. carry += i < len_b ? (b[i] == '1') : 0;
  17. ans[len++] = carry % 2 + '0';
  18. carry /= 2;
  19. }
  20. if (carry) {
  21. ans[len++] = '1';
  22. }
  23. ans[len] = '\0';
  24. reserve(ans);
  25. return ans;
  26. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/538789
推荐阅读
相关标签
  

闽ICP备14008679号