博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode——Add Binary
阅读量:6991 次
发布时间:2019-06-27

本文共 801 字,大约阅读时间需要 2 分钟。

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

For example,

a = "11"
b = "1"

Return "100".

求数字字符串的二进制和。

同之前的数组代表数字,两个数组相加一样。仅仅只是进位变成了2.可能两个串的长度不一样,故逆转。从左到右加下去。最后再逆转。

public static String addBinary(String a, String b) {		StringBuilder ar = new StringBuilder(a).reverse();		StringBuilder br = new StringBuilder(b).reverse();		StringBuilder result = new StringBuilder();		int len = Math.max(a.length(), b.length());		int carry = 0;//进位		for (int i = 0; i < len; i++) {			int t1 = (i >= a.length() ? 0 : (ar.charAt(i) - '0'));			int t2 = (i >= b.length() ? 0 : (br.charAt(i) - '0'));			int t3 = t1 + t2 + carry;			carry = t3 / 2;			t3 = t3 % 2;			result.append(t3);		}		if (carry != 0)			result.append(carry);		result.reverse();		return result.toString();	}

版权声明:本文博客原创文章。博客,未经同意,不得转载。

你可能感兴趣的文章
while(scanf("%d",&n)!=EOF)与while(cin>>n)
查看>>
BigTale
查看>>
UITabBarController 笔记(一)AppDelegate中加UITabBarController 为 rootViewController
查看>>
oracle基础备份和还原
查看>>
Velocity 语法示例
查看>>
golang的ssh例子
查看>>
【python】pymongo中正则查询时的转义问题
查看>>
立足“快时尚”,联想笋尖S90怎样诠释“比美更美”?
查看>>
linux下执行strlwr函数出错:ld returned 1 exit status
查看>>
WSADATA
查看>>
各大引擎矩阵的矩阵存储方式 ----行矩阵 or 列矩阵
查看>>
html 跳转页面,同时跳转到一个指定的位置
查看>>
solr的suggest模块
查看>>
SWT中ole/activex实践--操作word的一个例子
查看>>
Volley(二)—— 基本Request对象 & RequestQueue&请求取消
查看>>
arguments对象的实例使用
查看>>
easyui datalist按组多选
查看>>
Python-代码对象
查看>>
Xcode界面切换动画效果
查看>>
StackExchange.Redis 访问封装类
查看>>