LeetCode Add Binary(二进制加法)
2016-06-22 14:18
351 查看
思路:大整数加法
代码如下:
public class Solution
{
public String addBinary(String a, String b)
{
StringBuilder sb = new StringBuilder();
int i;
int c = 0;
StringBuilder a1 = new StringBuilder(a).reverse();
StringBuilder b1 = new StringBuilder(b).reverse();
for (i = 0; i < a1.length() && i < b1.length(); i++)
{
int num1 = a1.charAt(i) - '0';
int num2 = b1.charAt(i) - '0';
int sum = num1 + num2 + c;
c = sum / 2;
sum %= 2;
sb.append((char)('0' + sum));
}
String tmp;
if (i >= a1.length()) tmp = b1.toString();
else tmp = a1.toString();
for (; i < tmp.length(); i++)
{
int num1 = tmp.charAt(i) - '0';
int sum = num1 + c;
c = sum / 2;
sum %= 2;
sb.append((char)('0' + sum));
}
if (c != 0)
{
sb.append((char)('0' + c));
}
return sb.reverse().toString();
}
}
代码如下:
public class Solution
{
public String addBinary(String a, String b)
{
StringBuilder sb = new StringBuilder();
int i;
int c = 0;
StringBuilder a1 = new StringBuilder(a).reverse();
StringBuilder b1 = new StringBuilder(b).reverse();
for (i = 0; i < a1.length() && i < b1.length(); i++)
{
int num1 = a1.charAt(i) - '0';
int num2 = b1.charAt(i) - '0';
int sum = num1 + num2 + c;
c = sum / 2;
sum %= 2;
sb.append((char)('0' + sum));
}
String tmp;
if (i >= a1.length()) tmp = b1.toString();
else tmp = a1.toString();
for (; i < tmp.length(); i++)
{
int num1 = tmp.charAt(i) - '0';
int sum = num1 + c;
c = sum / 2;
sum %= 2;
sb.append((char)('0' + sum));
}
if (c != 0)
{
sb.append((char)('0' + c));
}
return sb.reverse().toString();
}
}
相关文章推荐
- FPGA入门的基础知识
- MVC 区域内默认控制器不能访问(Multiple types were found that match the controller named ‘Index')
- Lnmp中nginx经常出现502错误解决方法
- memcpy函数详解
- 从平庸到卓越!5个帮你快速提高设计稿质感的实用方法
- oracle数据库system密码忘记怎么办?
- 营销案例,只保留一天,马上要删
- Java代码实现设置系统时间
- nginx安装及配置
- IOException while loading persisted sessions: java.io.EOFException异常的解决办法
- html禁止Input文本输入缓存的两种方法
- android 文件缓存 DiskLruCache
- 倒立三角打印
- 构建一个属于你自己的镜像
- 刚入职服务器就被攻击,如何治愈与防范【吐血经历】
- Excel表格技巧(逆了天的39个非常牛逼的技巧)
- Java编程中“为了性能”需做的26件事
- JQuery miscellany 整理
- pdf转图片
- ZooKeeper安装与配置