您的位置:首页 > 科技 > IT业 > leetcode67 二进制求和

leetcode67 二进制求和

2024/10/6 14:30:22 来源:https://blog.csdn.net/2402_84062759/article/details/139728474  浏览:    关键词:leetcode67 二进制求和

给你两个二进制字符串 a 和 b ,以二进制字符串的形式返回它们的和。

示例 1:

输入:a = "11", b = "1"
输出:"100"

示例 2:

输入:a = "1010", b = "1011"
输出:"10101"
class Solution {public String addBinary(String a, String b) {if(a.length()==0) return b;if(b.length()==0) return a;String s = "";String ca = new StringBuffer(a).reverse().toString();String cb = new StringBuffer(b).reverse().toString();int t=0;int i=0;while (i<ca.length() && i<cb.length()){t += (ca.charAt(i)-'0') + (cb.charAt(i)-'0');s += Integer.toString(t%2);t=t/2;i++;}while (i<ca.length()){t += (ca.charAt(i)-'0');s += Integer.toString(t%2);t=t/2;i++;}while (i<cb.length()){t += (cb.charAt(i)-'0');s += Integer.toString(t%2);t=t/2;i++;}if(t!=0) s+='1';return new StringBuffer(s).reverse().toString();}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com