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

Commitc8026a5

Browse files
author
applewjg
committed
Add Binary'
1 parent320c6c9 commitc8026a5

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎AddBinary.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 12, 2014
4+
Problem: Add Binary
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/add-binary/
7+
Notes:
8+
Given two binary strings, return their sum (also a binary string).
9+
For example,
10+
a = "11"
11+
b = "1"
12+
Return "100".
13+
14+
Solution: '1'-'0' = 1.
15+
*/
16+
17+
publicclassSolution {
18+
publicStringaddBinary(Stringa,Stringb) {
19+
StringBufferres =newStringBuffer();
20+
intN =a.length(),M =b.length();
21+
inti =N -1,j =M -1;
22+
intcarry =0;
23+
while (i>=0 ||j>=0) {
24+
intsum =carry;
25+
if (i >=0)sum +=a.charAt(i--) -'0';
26+
if (j >=0)sum +=b.charAt(j--) -'0';
27+
carry =sum /2;
28+
res.insert(0,String.valueOf(sum %2));
29+
}
30+
if (carry ==1)res.insert(0,'1');
31+
returnres.toString();
32+
}
33+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp