C++实现LeetCode(67.二进制数相加)

[LeetCode] 67. Add Binary 二进制数相加

Given two binary strings a and b, return their sum as a binary string.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

二进制数相加,并且保存在 string 中,要注意的是如何将 string 和 int 之间互相转换,并且每位相加时,会有进位的可能,会影响之后相加的结果。而且两个输入 string 的长度也可能会不同。这时我们需要新建一个 string,它的长度是两条输入 string 中的较大的那个,并且把较短的那个输入 string 通过在开头加字符 ‘0' 来补的较大的那个长度。这时候逐个从两个 string 的末尾开始取出字符,然后转为数字,想加,如果大于等于2,则标记进位标志 carry,并且给新 string 加入一个字符 ‘0'。代码如下:

解法一:

class Solution {
public:
    string addBinary(string a, string b) {
        string res;
        int na = a.size(), nb = b.size(), n = max(na, nb), carry = 0;
        if (na > nb) {
            for (int i = 0; i < na - nb; ++i) b.insert(b.begin(), '0');
        } else {
            for (int i = 0; i < nb - na; ++i) a.insert(a.begin(), '0');
        }
        for (int i = n - 1; i >= 0; --i) {
            int sum = (a[i] - '0') + (b[i] - '0') + carry;
            res = to_string(sum % 2) + res;
            carry = sum / 2;
        }
        if (carry) res.insert(res.begin(), '1');
        return res;
    }
};

下面这种写法又巧妙又简洁,用了两个指针分别指向a和b的末尾,然后每次取出一个字符,转为数字,若无法取出字符则按0处理,然后定义进位 carry,初始化为0,将三者加起来,对2取余即为当前位的数字,对2取商即为当前进位的值,记得最后还要判断下 carry,如果为1的话,要在结果最前面加上一个1,参见代码如下:

解法二:

class Solution {
public:
    string addBinary(string a, string b) {
        string res = "";
        int m = a.size() - 1, n = b.size() - 1, carry = 0;
        while (m >= 0 || n >= 0) {
            int p = m >= 0 ? a[m--] - '0' : 0;
            int q = n >= 0 ? b[n--] - '0' : 0;
            int sum = p + q + carry;
            res = to_string(sum % 2) + res;
            carry = sum / 2;
        }
        return carry == 1 ? "1" + res : res;
    }
};

到此这篇关于C++实现LeetCode(67.二进制数相加)的文章就介绍到这了,更多相关C++实现二进制数相加内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(62.不同的路径)

    [LeetCode] 62. Unique Paths 不同的路径 A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner

  • C++实现LeetCode(64.最小路径和)

    [LeetCode] 64. Minimum Path Sum 最小路径和 Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in t

  • C++实现LeetCode(189.旋转数组)

    [LeetCode] 189. Rotate Array 旋转数组 Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate

  • C++实现LeetCode(174.地牢游戏)

    [LeetCode] 174. Dungeon Game 地牢游戏 The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the t

  • C++实现LeetCode(70.爬楼梯问题)

    [LeetCode] 70. Climbing Stairs 爬楼梯问题 You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Examp

  • C++实现LeetCode(66.加一运算)

    [LeetCode] 66. Plus One 加一运算 Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the a

  • C++实现LeetCode(63.不同的路径之二)

    [LeetCode] 63. Unique Paths II 不同的路径之二 A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right c

  • C++实现LeetCode(67.二进制数相加)

    [LeetCode] 67. Add Binary 二进制数相加 Given two binary strings a and b, return their sum as a binary string. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: &q

  • C++实现LeetCode(2.两个数字相加)

    [LeetCode] 2. Add Two Numbers 两个数字相加 You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked

  • PHP两个n位的二进制整数相加问题的解决

    两个n位的二进制整数相加问题PHP实现,供大家参考,具体内容如下 两个n位二进制数分别存储在两个n元数组A和B中,这两个整数的和存在一个n+1元的数组C中 答: 此问题主要是考察相加进位的问题,元素1+1 =0 并且往前进一位 ADD-BINARY(A,B) C=new integer[A.length+1] carry=0 for i=A.length downto 1 C[i+1]=(A[i]+B[i]+carry)%2 carry=(A[i]+B[i]+carry)/2 C[i]=carr

  • go语言的四数相加等于指定数算法

    给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0. 首先将四个数组分割为两两数组,前两个数组值相加,后两个数组相加,入股前两个数组相加和与后两个数组相加和正好为相反数,四个元素之和为0. 首先: 将两数组的元素进行遍历相加,相加之和为map的索引.所指向的元素,就是出现的次数. func foursumcount(A []int, B []int, C []int, D []i

  • C++实现算法两个数字相加详解

    Add Two Numbers 两个数字相加 You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers

  • C++实现LeetCode(两个有序数组的中位数)

    [LeetCode] 4. Median of Two Sorted Arrays 两个有序数组的中位数 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and 

  • C++实现LeetCode(13.罗马数字转化成整数)

    [LeetCode] 13. Roman to Integer 罗马数字转化成整数 Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol       Value I                  1 V                 5 X                10 L                 50 C                100 D 

  • C++实现LeetCode(43.字符串相乘)

    [LeetCode] 43. Multiply Strings 字符串相乘 Given two non-negative integers num1 and num2represented as strings, return the product of num1 and num2, also represented as a string. Example 1: Input: num1 = "2", num2 = "3" Output: "6"

  • C++实现LeetCode(89.格雷码)

    [LeetCode] 89.Gray Code 格雷码 The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code se

随机推荐