Java [Leetcode 67]Add Binary
题目描述:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
解题思路:
使用StringBuilder,且使用进位。
代码如下:
public class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
while(i >= 0 || j >= 0){
if(i >= 0) carry += a.charAt(i--) - '0';
if(j >= 0) carry += b.charAt(j--) - '0';
sb.insert(0, carry % 2);
carry /= 2;
}
if(carry > 0) sb.insert(0, carry);
return sb.toString();
}
}
Java [Leetcode 67]Add Binary的更多相关文章
- LeetCode 67. Add Binary (二进制相加)
Given two binary strings, return their sum (also a binary string). For example,a = "11"b = ...
- [LeetCode] 67. Add Binary 二进制数相加
Given two binary strings, return their sum (also a binary string). The input strings are both non-em ...
- LeetCode 67. Add Binary
Given two binary strings, return their sum (also a binary string). For example,a = "11"b = ...
- (String) leetcode 67. Add Binary
Given two binary strings, return their sum (also a binary string). The input strings are both non-em ...
- [leetcode]67. Add Binary 二进制加法
Given two binary strings, return their sum (also a binary string). The input strings are both non-em ...
- LeetCode - 67. Add Binary(4ms)
Given two binary strings, return their sum (also a binary string). The input strings are both non-em ...
- leetcode 67. Add Binary (高精度加法)
Given two binary strings, return their sum (also a binary string). For example,a = "11"b = ...
- LeetCode 67 Add Binary(二进制相加)(*)
翻译 给定两个二进制字符串,返回它们的和(也是二进制字符串). 比如, a = "11" b = "1" 返回 "100". 原文 Give ...
- leetCode 67.Add Binary (二进制加法) 解题思路和方法
Given two binary strings, return their sum (also a binary string). For example, a = "11" b ...
随机推荐
- ajax与jsonp的区别
ajax的核心是通过XmlHttpRequest获取非本页内容,而jsonp的核心则是动态添加<script>标签来调用服务器提供的js脚本.
- 【WCF--初入江湖】10 序列化和传输大型数据流
10 序列化和传输大型数据流 1.前言 理解WCF的序列化形式 掌握DataContractSerializer序列化对象 比较性能 比较xmlSerializer序列化对象 大数据量传输设置 修 ...
- StringBuffer用法
public class StringBufferTest { public static void main(String[] args) { StringBuffer sb=new StringB ...
- HDU 1301 Jungle Roads (最小生成树,基础题,模版解释)——同 poj 1251 Jungle Roads
双向边,基础题,最小生成树 题目 同题目 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include<stri ...
- POJ 1781
#include <iostream> #include <string> #include <cmath> using namespace std; unsign ...
- POJ 1724 ROADS(BFS+优先队列)
题目链接 题意 : 求从1城市到n城市的最短路.但是每条路有两个属性,一个是路长,一个是花费.要求在花费为K内,找到最短路. 思路 :这个题好像有很多种做法,我用了BFS+优先队列.崔老师真是千年不变 ...
- cojs 西瓜 解题报告
首先我们要知道pick公式 设二维平面内任意多边形面积为S 设多边形内部整点数为a 设多边形边界的整点数为b 则满足S=a+b/2-1 变形得a=S-b/2+1 由期望的线性性质我们把问题转化为 1. ...
- BZOJ 3203 sdoi 2013 保护出题人
由于样例解释很清晰,所以很容易得到以下结论: 1.每一关都是独立的,且僵尸的相对位置不会变 2.每一关的攻击力=Max(sum(i)/dis(i)) 其实sum(i)是僵尸攻击力的前缀和,dis(i) ...
- 【Linux高频命令专题(22)】gzip
概述 减少文件大小有两个明显的好处,一是可以减少存储空间,二是通过网络传输文件时,可以减少传输的时间.gzip是在Linux系统中经常使用的一个对文件进行压缩和解压缩的命令,既方便又好用.gzip不仅 ...
- scanf()函数用法小结
scanf()函数是格式化输入函数,它从标准输入设备(键盘) 读取输入的信息. 其调用格式为: scanf("<格式化字符串>",<地址表>); ...