Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commiteced7a5

Browse files
EASY/src/easy/AddBinary.java
1 parent6cc7efc commiteced7a5

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

‎EASY/src/easy/AddBinary.java

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,23 @@ public class AddBinary {
1414
//Tricks and things learned that could be learned:
1515
//1. use StringBuilder.reverse() function! Nice!
1616
//2. if a numeric number is represented/stored in String, how to get its value: use Character.getNumericValue(s.charAt(i))
17-
//3. directly adding/subtracting chars will end up working with their ASCII numbers, e.g. chars[0] = 'a', chars[1] = 'b', then chars[0] + chars[1] will become 195
17+
//3. directly adding/subtracting chars will end up working with their ASCII numbers, e.g. chars[0] = 'a', chars[1] = 'b', then chars[0] + chars[1] will become 195
18+
publicStringaddBinary(Stringa,Stringb){
19+
intcarry =0,i =a.length()-1,j =b.length()-1;
20+
StringBuildersb =newStringBuilder();
21+
while(i >=0 ||j >=0){
22+
intsum =carry;
23+
if(i >=0)sum +=a.charAt(i--) -'0';
24+
if(j >=0)sum +=b.charAt(j--) -'0';
25+
sb.append(sum%2);
26+
carry =sum/2;
27+
}
28+
if(carry !=0)sb.append(carry);
29+
returnsb.reverse().toString();
30+
}
1831

1932
//my original lengthy but AC'ed solution
20-
publicStringaddBinary(Stringa,Stringb) {
33+
publicStringaddBinary_my_original_accepted_but_lengthy_solution(Stringa,Stringb) {
2134
char[]longer = (a.length() >=b.length()) ?a.toCharArray() :b.toCharArray();
2235
char[]shorter = (a.length() <b.length()) ?a.toCharArray() :b.toCharArray();
2336
//at the maximum, the result length will be Math.max(a.length, b.length)+1;

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp