leetcode 67. Add Binary
来源:互联网 发布:centos安装hadoop2.6 编辑:程序博客网 时间:2024/06/06 14:10
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
和上一道题一样,不过这里是按照二进制的加法。
代码如下:
public class Solution { public String addBinary(String a, String b) { a=a.trim(); b=b.trim(); if(a.length()<=0) return b; if(b.length()<=0) return a; int lena=a.length(); int lenb=b.length(); if(lena>lenb) { String tt=a; a=b; b=tt; } lena=a.length(); lenb=b.length(); String res=""; int jinwei=0,i=lena-1,j=lenb-1; for(i=lena-1;i>=0;i--) { int sum=Integer.parseInt(a.charAt(i)+"")+Integer.parseInt(b.charAt(j)+"")+jinwei; j--; res=(sum%2)+res; jinwei=sum/2; } for(i=j;i>=0;i--) { int sum=Integer.parseInt(b.charAt(i)+"")+jinwei; res=(sum%2)+res; jinwei=sum/2; } if(jinwei<=0) return res; else { res=jinwei+res; return res; } }}
C++的答案如下,和上一道题一样,很简单
代码如下:
#include <iostream>#include <sstream>using namespace std;class Solution {public: string addBinary(string a, string b) { string res = ""; int i = a.length() - 1 , j = b.length() - 1; int jinwei = 0; while (i >= 0 && j >= 0) { int x = (int)(a[i--] - '0'); int y = (int)(b[j--] - '0'); int sum = x + y + jinwei; jinwei = sum / 2; res = to_string(sum % 2) + res; } while (i >= 0) { int x = (int)(a[i--] - '0'); int sum = x + jinwei; jinwei = sum / 2; res = to_string(sum % 2) + res; } while (j >= 0) { int y = (int)(b[j--] - '0'); int sum = y + jinwei; jinwei = sum / 2; res = to_string(sum % 2) + res; } if(jinwei>0) res = to_string(jinwei) + res; return res; }};
阅读全文
0 0
- [LeetCode]67.Add Binary
- LeetCode --- 67. Add Binary
- [Leetcode] 67. Add Binary
- [leetcode] 67.Add Binary
- 【leetcode】67. Add Binary
- [leetcode] 67.Add Binary
- [leetcode] 67. Add Binary
- 【Leetcode】67. Add Binary
- 67. Add Binary LeetCode
- 【LeetCode】67. Add Binary
- leetcode--67. Add Binary
- leetcode 67. Add Binary
- LeetCode 67. Add Binary
- LeetCode *** 67. Add Binary
- leetcode 67. Add Binary
- 【leetcode】67.Add Binary
- LeetCode 67. Add Binary
- LeetCode-67.Add Binary
- TrinityCore 7.2.5 编译备忘录
- 关于lua垃圾回收器的理解
- C#转换国内省市区,文本内容来自某area.json文件
- 免安装版MySQL(3)修改初始密码命令
- Springboot filter 拦截指定的路径(注入spring Bean方式)
- leetcode 67. Add Binary
- python爬虫之pymysql库的使用(2)
- Java实习生在项目中遇到的问题
- Java实现验证码的制作
- android studio 汉化包 美化包
- Xamarin Studio
- 数据结构与算法(3)---Java语言实现:栈的单链表定义
- SQL优化之四两拨千金
- Tkinter之Event篇