[LeetCode] 67. Add Binary Java
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] 67. Add Binary Java
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目:
Given two binary strings, return their sum (also a binary string).
For example,
a =?"11"
b =?"1"
Return?"100".
題意及分析:求兩個(gè)用字符串表示 的二進(jìn)制數(shù)的和。主要是判斷每次相加的和是否大于2,大于2便進(jìn)1取余。
代碼:
class Solution {public String addBinary(String a, String b) {String temp = "";int i = a.length()-1,j=b.length()-1;int count = 0;while(i>=0&& j>=0){count = count + (a.charAt(i)-'0') + (b.charAt(j)-'0');if(count > 1){temp = ((count)%2) + temp;count = 1;}else{temp = count + temp;count = 0;}i--;j--;}//a長(zhǎng)一些while(i>=0){count += a.charAt(i)-'0';if(count > 1){temp = ((count)%2) + temp;count = 1;}else{temp = count + temp;count = 0;}i--;}//b長(zhǎng)一些while(j>=0){count += b.charAt(j)-'0';if(count > 1){temp = ((count)%2) + temp;count = 1;}else{temp = count + temp;count = 0;}j--;}if(count == 1)temp = count + temp;return temp;} }?
?
轉(zhuǎn)載于:https://www.cnblogs.com/271934Liao/p/8249700.html
總結(jié)
以上是生活随笔為你收集整理的[LeetCode] 67. Add Binary Java的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Linux 播放网易云音乐(树莓派)
- 下一篇: 洛谷P3391文艺平衡树(Splay)