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 ...
随机推荐
- ASP.NET MVC 4 插件化架构简单实现-实例篇
先回顾一下上篇决定的做法: 1.定义程序集搜索目录(临时目录). 2.将要使用的各种程序集(插件)复制到该目录. 3.加载临时目录中的程序集. 4.定义模板引擎的搜索路径. 5.在模板引擎的查找页面方 ...
- Java7 新特性 数值文本表示法
今天和大家分享下 java7中新特性-数值文本表示法 首先,在原来jdk1.6中 如果需要将一个二进制的数值转换成十进制的话,一般情况下都会以下面的代码方式去实现. public static voi ...
- Matlab中mat2cell的使用
怎样用mat2cell将一个100*100的矩阵分成10个10*100的矩阵? 根据帮助中 c = mat2cell(x,m,n)应该这样写 mat2cell(x,[10 10 10 10 10 10 ...
- 剑指offer--面试题9
题目一:求斐波那契数列第n项 自己所写代码如下: #include "stdafx.h" #include<iostream> long Fibonacci(unsig ...
- WPF 显示初始化界面
今天在看<WPF编程宝典>时,看到了Application类,该类可以做很多事情,我认为比较实用的是显示初始化界面,因为之前有个项目在打开的时候要加载好多dll,非常耗时,让客户等的蛋疼, ...
- spoj 1108
要求输出一个牌的顺序 使每隔1.2.......n翻牌后出现1 2 3 4 5 6 7 8 9 .... n 将牌想象成n个空格 正向推 空n个位置放n 循环 需优化 #include <io ...
- StringTokenizer用法
import java.util.StringTokenizer; public class StringTokenizerTest { public static void main(String[ ...
- Javascript 绝对定位和相对定位
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- notepad++每行首尾添加内容
有时候我们需要给一个文本文件的每行前面或后面添加一些内容,例如我们一个文本文件里存放了很多图片的地址,现在我们需要把这些图片批量转换成html标记 百度经验:jingyan.baidu.com 工具/ ...
- Mmap的实现原理和应用
http://blog.csdn.net/edwardlulinux/article/details/8604400 很多文章分析了mmap的实现原理.从代码的逻辑来分析,总是觉没有把mmap后读写映 ...