【LeetCode】66 & 67- Plus One & Add Binary

66 - Plus One

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

Solution 1 : 十进制加法

 class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int carry = ;
for(int i = digits.size()-; i >= ; i --)
{
int sum = digits[i]+carry;
carry = sum / ;
digits[i] = sum % ;
if(carry == )
break;
}
if(carry == )
digits.insert(digits.begin(), );
return digits;
}
};

Solution 2 :

 class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
for(int i = digits.size()-; i >= ; i --)
{
if(digits[i] <= ){
digits[i] += ;
return digits;
}else{//
if(i != )
digits[i] = ;
else
{
digits[] = ;
digits.push_back();
return digits;
}
}
}
}
};

67- Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

Solution:二进制加法,和为2进1,和为3进1留1;

【LeetCode】66 & 67- Plus One & Add Binary
 1 class Solution {
2 public:
3 string addBinary(string a, string b) {
4 int sizea=a.size(),sizeb=b.size();
5 if(sizea<sizeb)return addBinary(b,a);
6 int n=sizea-sizeb;
7 string helper(n,'0');
8 b = helper + b;
9 int carry=0;
10 for(int i=sizea-1;i>=0;i--){
11 int sum=(a[i]-'0')+(b[i]-'0')+carry;
12 if(sum==0);
13 else if(sum==1){
14 a[i]='1';
15 carry=0;
16 }else if(sum==2){
17 a[i]='0';
18 carry=1;
19 }else if(sum==3){
20 a[i]='1';
21 carry=1;
22 }
23 }
24 if(carry==1)a='1'+a;
25 return a;
26 }
27 };
【LeetCode】66 & 67- Plus One & Add Binary
上一篇:redhat Enterprise Linux Server release 7.2(Maipo) 安装redis-stat


下一篇:webpack v3 结合 react-router v4 做 dynamic import — 按需加载(懒加载)