zoukankan      html  css  js  c++  java
  • Leetcode#67 Add Binary

    原题地址

    简单模拟题

    代码:

     1 string addBinary(string a, string b) {
     2         int i = a.length() - 1;
     3         int j = b.length() - 1;
     4         int carry = 0;
     5         string sum;
     6         
     7         while (i >= 0 && j >= 0) {
     8             sum += ((a[i] - '0') + (b[j] - '0') + carry) % 2 + '0';
     9             carry = ((a[i] - '0') + (b[j] - '0') + carry) / 2;
    10             i--;
    11             j--;
    12         }
    13         
    14         while (i >= 0) {
    15             sum += ((a[i] - '0') + carry) % 2 + '0';
    16             carry = ((a[i] - '0') + carry) / 2;
    17             i--;
    18         }
    19         
    20         while (j >= 0) {
    21             sum += ((b[j] - '0') + carry) % 2 + '0';
    22             carry = ((b[j] - '0') + carry) / 2;
    23             j--;
    24         }
    25         
    26         if (carry > 0)
    27             sum += '1';
    28         
    29         i = 0;
    30         while (i * 2 < sum.length()) {
    31             swap(sum[i], sum[sum.length() - 1 - i]);
    32             i++;
    33         }
    34         
    35         return sum;
    36 }
  • 相关阅读:
    day 01
    day14
    day12
    day13
    day11
    day9
    day10
    day08
    day07
    day06
  • 原文地址:https://www.cnblogs.com/boring09/p/4266864.html
Copyright © 2011-2022 走看看