当前位置:网站首页>LeetCode——Add Binary

LeetCode——Add Binary

2022-07-05 23:16:00 Full stack programmer webmaster

Hello everyone , I meet you again , I'm the king of the whole stack

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

For example, a = "11" b = "1"

Return "100".

Find the binary sum of numeric strings .

The same as the previous array represents numbers , The addition of two arrays is the same . Only the carry becomes 2. Maybe the length of the two strings is different , So reverse . Add from left to right . Finally, reverse .

	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;// carry 
		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();
	}

Copyright notice : This article is an original blog article . Blog , Without consent , Shall not be reproduced .

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/117531.html Link to the original text :https://javaforall.cn

原网站

版权声明
本文为[Full stack programmer webmaster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207052301272416.html