Leetcode题解(22)

66. Plus One

题目

Leetcode题解(22)_第1张图片

这题很简单,直接代码:

 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int> &digits) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         int a = 1;
 7         vector<int> ans;
 8         vector<int>::iterator it;
 9         for(int i = digits.size() - 1;i >= 0;i--)
10         {
11             it = ans.begin();
12             int b = (a + digits[i]) % 10;
13             a = (a + digits[i]) / 10;
14             ans.insert(it, b);
15         }
16         if(a != 0)
17         {
18             it = ans.begin();
19             ans.insert(it, a);
20         }
21         
22         return ans;
23     }
24 };

------------------------------------------------------------------------------------分割线--------------------------------------------------------------

67. Add Binary

题目

Leetcode题解(22)_第2张图片

直接代码

 1 class Solution {
 2   public:
 3       string addBinary(string a, string b) {
 4           int lenA,lenB;
 5           lenA = a.length();
 6           lenB = b.length();
 7           string res="";
 8           
 9 
10           if (0 == lenA)
11           {
12               return b;
13           }
14           if (0 == lenB)
15           {
16               return a;
17           }
18           int ia=lenA-1,ib=lenB-1;
19           int count=0,temp;//进位
20           char c;
21           while (ia>=0&&ib>=0)
22           {
23               temp = a[ia]-'0'+b[ib]-'0'+count;
24               count = temp/2;
25               c = temp%2+'0';
26               res = c+res;
27               ia--;
28               ib--;
29           }
30 
31           while (ia>=0)
32           {
33               temp = a[ia]-'0'+count;
34               count = temp/2;
35               c = temp%2+'0';
36               res = c+res;
37               ia--;
38           }
39 
40           while (ib>=0)
41           {
42               temp = b[ib]-'0'+count;
43               count = temp/2;
44               c = temp%2+'0';
45               res = c+res;
46               ib--;
47           }
48           if(count != 0)
49           {
50               c=count+'0';
51               res = c+res;
52           }
53           return res;
54 
55       }
56   };

 

你可能感兴趣的:(Leetcode题解(22))