LEETCODE-Add Binary
2015-09-01 11:58
351 查看
leetcode
Add Binary:
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
对string类型的数据认识还不够完全,以后还要继续深入了解(准备入手一本C++primer)。
另外在写代码的过程中出现很多“小插曲”,用心写代码,杜绝低级错误。
之前浪费了很多时间没有抓住机会提高自己的能力,现在我要好好写代码,找到代码的乐趣。
https://leetcode.com/submissions/detail/38375877/
Add Binary:
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
#include<stdio.h> #include<iostream> #include<cstring> #define MAXN 300+10 using namespace std; string Add(string a,string b) { if(a[0] == 48 &&b[0] == 48) return a; else{ int num1[MAXN] = {0},num2[MAXN] = {0}; int len1 = a.size(); int len2 = b.size(); int i=0,j=0; for(i = len1-1,j = 0;i >= 0;i--) num1[j++] = a[i] - '0'; for(i = len2-1,j = 0;i >= 0;i--) num2[j++] = b[i]-'0'; for(i = 0;i < MAXN;i++) { num1[i] += num2[i]; if(num1[i] >= 2) { num1[i] -=2; num1[i+1]++; } } int wh = MAXN-1; while(num1[wh] == 0) wh--; string c; for(int k = wh;k >= 0;k--) c += num1[k] + '0'; a = c; return a; printf("\n"); } } int main() { string s1,s2; cin >> s1; cin >> s2; string s3; s3 = Add(s1,s2); cout << s3; return 0; }
对string类型的数据认识还不够完全,以后还要继续深入了解(准备入手一本C++primer)。
另外在写代码的过程中出现很多“小插曲”,用心写代码,杜绝低级错误。
之前浪费了很多时间没有抓住机会提高自己的能力,现在我要好好写代码,找到代码的乐趣。
https://leetcode.com/submissions/detail/38375877/
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解