Java for LeetCode 067 Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
解题思路:
JAVA实现如下:
static public String addBinary(String a, String b) {if (a.length() < b.length()) {String temp = a;a = b;b = temp;}boolean carry = false;StringBuilder sb = new StringBuilder(a);for (int i = 0; i < b.length(); i++) {if (b.charAt(b.length() - 1 - i) == '0') {if (sb.charAt(a.length() - 1 - i) == '0' && carry) {sb.replace(a.length() - 1 - i, a.length() - i, "1");carry = false;} else if (sb.charAt(a.length() - 1 - i) == '1' && carry)sb.replace(a.length() - 1 - i, a.length() - i, "0");} else {if (sb.charAt(a.length() - 1 - i) == '0' && !carry)sb.replace(a.length() - 1 - i, a.length() - i, "1");else if (sb.charAt(a.length() - 1 - i) == '1' && !carry) {sb.replace(a.length() - 1 - i, a.length() - i, "0");carry = true;}}}if (!carry)return sb.toString();for (int i = a.length() - b.length() - 1; i >= 0; i--)if (sb.charAt(i) == '0') {sb.replace(i, i + 1, "1");return sb.toString();} elsesb.replace(i, i + 1, "0");sb.insert(0, '1');return sb.toString();}
转载于:https://www.cnblogs.com/tonyluis/p/4507624.html
Java for LeetCode 067 Add Binary相关推荐
- leetcode 67 Add Binary
Add Binary Total Accepted: 46815 Total Submissions: 189215 My Submissions Given two binary strings, ...
- [LeetCode]67.Add Binary
[题目] Given two binary strings, return their sum (also a binary string). For example, a = "11&qu ...
- LeetCode 67. Add Binary
67. Add Binary My Submissions QuestionEditorial Solution Total Accepted: 81992 Total Submissions: 29 ...
- [LeetCode] 67. Add Binary Java
题目: Given two binary strings, return their sum (also a binary string). For example, a = "11&quo ...
- 067 Add Binary 二进制求和
给定两个二进制字符串,返回他们的和(用二进制表示). 案例: a = "11" b = "1" 返回 "100" . 详见:https:// ...
- Java for LeetCode 114 Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place. For example, Given 1/ \2 5/ \ \3 4 6 The ...
- java两个二进制数求和,Leetcode 67:Add Binary(二进制求和)
Leetcode 67:Add Binary(二进制求和) (python.java) Given two binary strings, return their sum (also a binar ...
- LeetCode刷题记录4——67. Add Binary(easy)
LeetCode刷题记录4--67. Add Binary(easy) 目录 LeetCode刷题记录4--67. Add Binary(easy) 题目 语言 思路 后记 题目 今天这题是与字符串相 ...
- LeetCode: Add Binary 解题报告
Add Binary Given two binary strings, return their sum (also a binary string). For example, a = " ...
最新文章
- 中国人工智能计划,我来说几句
- struts文件上传
- 前端模块管理器命令:npm bower
- asp.net %% %#%%=%%@%%$%用法与区别
- Common Used Excel Formulas
- Python环境搭建之OpenCV(转载)
- 拓端tecdat|Python高维统计建模变量选择:SCAD平滑剪切绝对偏差惩罚、Lasso惩罚函数比较
- C# 2.0泛型编程基础(1)
- [开源工具] 串口转wifi —— 两个串口之间通过网络进行通信
- MAXScript入门
- 自己做网站需要考虑的问题
- S7-200PLC寄存器寻址
- tornado 异步
- 数据结构 - 线性表顺序存储结构
- 毫米焦距到像素焦距换算
- typescript总结
- 日拱一卒,“功不唐捐
- 建好这个“群”,建设郑州国家中心城市成首要突破口
- 专注中小企业 ERP 系统解决方案(源码JavaVue)
- 数据库系统概论-第一章绪论【概念模型、层次模型和三级模式(外模式、模式、内模式)】