public String addBinary(String a, String b) { int x = Integer.parseInt(a, 2); int y = Integer.parseInt(b, 2); return Integer.toBinaryString(x + y); }
一开始直接用Integer.toBinaryString()和Integer.parseInt(String, int)方法直接写。小例子还好,可是大例子就过不了,只能强行写了= =
public class Solution { public String addBinary(String a, String b) { int length = a.length(); if (b.length() > length) length = b.length(); String aa = "", bb = ""; StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length - a.length(); ++i) aa = aa + "0"; for (int i = 0; i < length - b.length(); ++i) bb = bb + "0"; aa = aa + a; bb = bb + b; char last = '0'; char cha, chb; int count = 0; for (int i = length - 1; i > -1; i--){ cha = aa.charAt(i); chb = bb.charAt(i); count = Character.forDigit(2,last) + Character.forDigit(2,cha) + Character.forDigit(2,chb); sb.setCharAt(i, Character.forDigit(2, count % 2)); last = Character.forDigit(2, count / 2); } if (last == '0') return sb.toString(); else return '1' + sb.toString(); } }
注意Character.forDigit是转换char的的方法,可是问题是StringBuilder为空的时候是不能用setCharAt方法的。。。唉
然后还有问题是forDigit写反了 有些还不是用forDigit而是用digit方法
public class Solution { public String addBinary(String a, String b) { int length = a.length(); if (b.length() > length) length = b.length(); String aa = "", bb = ""; StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; ++i) sb.append('0'); for (int i = 0; i < length - a.length(); ++i) aa = aa + "0"; for (int i = 0; i < length - b.length(); ++i) bb = bb + "0"; aa = aa + a; bb = bb + b; System.out.println(aa); System.out.println(bb); char last = '0'; char cha, chb; int count = 0; for (int i = length - 1; i > -1; i--) { cha = aa.charAt(i); chb = bb.charAt(i); System.out.println(cha + " " + chb); count = Character.digit(last, 2) + Character.digit(cha, 2) + Character.digit(chb, 2); System.out.println(count); sb.setCharAt(i, Character.forDigit(count % 2, 2)); last = Character.forDigit(count / 2, 2); } if (last == '0') return sb.toString(); else return '1' + sb.toString(); } }
对了Collections.frequency(Collection<T>, T object)方法可以统计某个object出现的次数
上面的代码其实还是出错 "Internal Error" 不知道为什么
下面找了个示例代码 显然要比我写的好很多啊唉。。。
public class Solution { public String addBinary(String a, String b) { // Start typing your Java solution below // DO NOT write main() function int l1 = a.length(), l2 = b.length(); StringBuilder sb = new StringBuilder(); int carry = 0; for (int i = 0; i < Math.max(l1, l2); i++) { int b1 = getBitAt(a, l1-1-i), b2 = getBitAt(b, l2-1-i); int sum = b1 + b2 + carry; sb.append(sum%2); carry = sum/2; } if (carry == 1) { sb.append(1); } return sb.reverse().toString(); } public int getBitAt(String s, int index) { if (index < 0) { return 0; } if (s.charAt(index) == '0') { return 0; } else { return 1; } } }
额 我现在想一下 要是开始把Integer改成Long,说不定就能过了测试了汗。。。当然还是不标准啦~
发表评论
-
Insert Interval
2012-11-11 01:33 543各种条件真复杂,不仅是边界条件,而且还要分很多种情况讨论 而且 ... -
Implement strStr()
2012-11-07 15:44 582唉 终于到了要记算法的时候了 KMP。。。还没写完 回去再写。 ... -
Flatten Binary Tree to Linked List && Generate Parentheses && Gray Code
2012-11-07 00:08 1093Flatten太简单了 递归 一遍过 oh yeah = = ... -
First Missing Positive
2012-11-06 22:50 589唉 想了很久都没想出来 后来还是看了网上的答案 >_&l ... -
Edit Distance
2012-11-06 00:27 670动规 就是递推。。。比较难想 然后数组长度设置比字符串长度多一 ... -
Divide Two Integers
2012-11-05 00:12 714自己实现除法 太太太恶心了。。。。 就是用位移代替了乘法,然后 ... -
Distinct Subsequences
2012-11-04 21:44 657动规,从前到后用T的每一个字符i,扫描S的每一个字符j。维护一 ... -
Count and Say
2012-11-04 18:46 693public class Solution { ... -
Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Sear
2012-11-04 17:36 826/** * Definition for binary ... -
Container With Most Water
2012-11-04 00:25 697本来以为是个简单的题目,直接二重循环,结果小测试过了,大测试超 ... -
Construct Binary Tree from Inorder and Postorder Traversal
2012-11-03 23:40 748不知道为什么错了。。。eclipse上明明是正确的啊 leet ... -
Combinations
2012-11-03 22:19 606全排列 按理说很简单,可是用递归写,边界条件就还是难想清楚,s ... -
Combination Sum I && II
2012-11-03 21:41 751还是递归 但是边界条件以及边界上的处理不容易搞清楚(一开始我就 ... -
climbing stairs
2012-11-03 17:18 610一开始觉得是简单的组合数学题,但是写完之后发现,首先组合数不是 ... -
Binary Tree Inorder Traversal
2012-11-02 23:51 615I简单 直接递归就好 addAll函数很好用 /** ... -
Best Time to Buy and Sell Stock I & II
2012-11-02 22:05 1045啊 第一次直接过small和big测试 好爽!虽然主要是以前知 ... -
Balanced Binary Tree
2012-11-01 23:38 610/** * Definition for binary ... -
Anagrams
2012-10-31 00:33 587这题实在是没懂它的意思。。。囧啊 import java. ... -
Add Two Numbers
2012-10-30 23:03 614这题不难 直接上递归就行 /** * Definiti ... -
4Sum
2012-10-27 22:49 734本来以为只要在3Sum外面再包一层循环就好了,可是。。。在Ju ...
相关推荐
leetCode 第67题。Swift解
python对图像提取mask部分: 代码: ...# Add binary masks to images for img_item in os.listdir(images_path): print(img_item) img_path = os.path.join(images_path, img_item) img = cv2.
Add Binary Longest Palindromic Substring Regular Expression Matching Wildcard Matching Longest Common Prefix Valid Number Integer to Roman Roman to Integer Count and Say Anagrams Valid Anagram ...
算法类,二进制加法的源代码,算法导论上的
401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./C++/binary-watch.cpp) [Python](./Python/binary-watch.py) | _O(1)_ | _O(1)_ | Easy | | 411 | [Minimum Unique Word ...
pod repo add binary_spec git@github.com:caixiang305621856/open_binary_spec.git 2.安装mongodb # 进入 /usr/local cd /usr/local # 下载 sudo curl -O ...
两个n位二进制数分别存储在两个n元数组A和B中,这两个整数的和存在一个n+1元的数组C中 答: 此问题主要是考察相加进位的问题,元素1+1 =0 并且往前进一位 ADD-BINARY(A,B) ...function addBinary($A
题目实现一个二进制加法,输入输出均为二进制字符串function binaryAdd(num1: string, num2: string): string {
leetcode ...Binary Linked-list 002 Add Two Numbers Stack 020 Valid Parenthesis Hash Table 001 TwoSum Reference 完整的学习流程 How to be a softwair engineer: 其他人详解 Python的各式演算法
67.二进制求和 (Add Binary) 69.x 的平方根 (Sqrt(x)) 70.爬楼梯 (Climbing Stairs) 83.删除排序链表中的重复元素 (Remove Duplicates from Sorted List) 88.合并两个有序数组 (Merge Sorted Array) 100.相同的树 ...
04-23从Alphabet到IntegerMapping的DecryptString 2020-04-25合并两个已排序的NodeList Fibonacci 2020-04-26查找ContinuousSequence MaximunNum 2020-04-28递归多态2020-04-30 HappyNumber 2020-05-01 AddBinary ...
AddBinary:从字符串中添加两个二进制数 AddTwoNumber:从数组中添加两个数字 BSTtoDLL:将二进制搜索树转换为双链表 BTreeIterator:二叉树迭代器:有序,前序,后序 BuildBT:从数组输入构建二进制 爬楼梯:爬...
addBinary longestPalindrome maximal rectangle :dp问题,较难 largestRectangleArea 求直方图的最大面积,左右两次扫面+剪枝优化 Valid Parentheses 用栈判断括号匹配 Regular Expression Matching 递归匹配 ...
leetcode双人赛LeetCode ...AddBinary :简单的问题。 AddTwoNumbers :简单的问题。 Anagrams :简单的#hashtable问题。 BalancedBinaryTree :简单的#balance #tree问题。 BestTimetoBuyandSellStock :简单的问题。 ...
所有题目源代码:Git地址 题目 给你两个二进制字符串,返回它们的和(用二进制表示)。 输入为 非空 字符串且只包含数字 1 和 0。 示例 1: 输入: a = 11, b = 1 ... public String addBinary(String a,
Introduction ============ This is a class to calculate histogram of LBP (local binary patterns) from an input image, histograms of...* Add the calculation of histogram of uniform rotation invariant VLBP.
此程序采用VHDL语言,完成在16位十六进制加法器的基础上将输出进行BCD码转换,实现输出是BCD码的16位二进制加法器
BinarySerializer ... AddFile ( new LinearSerializedFile ( context ) { FilePath = relativeFilePath }); 使用不同的BinaryFile类型,例如LinearSerializedFile , MemoryMappedFile和StreamF
此程序采用VHDL语言,完成在32位十六进制加法器的基础上将输出进行BCD码转换,实现输出是BCD码的32位二进制加法器
Work with Unity 5 and Unity 4.x ...– Add 3D Binary – Add 3D Computer – Add 3D Snow – Add 3D Black Hole – Add 3D Ghost Light – Add 3D Anomaly – Add 3D Shield – Add Atmosphere Fog – Add Pixelisat