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

Commit9670149

Browse files
authored
Merge pull requestneetcode-gh#1977 from Mahim1997/dev/67_Java
67. Add Binary
2 parents64091b7 +0f98cbd commit9670149

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

‎java/0067-Add-Binary.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
classSolution {
2+
publicStringaddBinary(Stringa,Stringb) {
3+
// Go from right to left
4+
intlen1 =a.length();
5+
intlen2 =b.length();
6+
7+
intminLen =Math.min(len1,len2);
8+
intmaxLen =Math.max(len1,len2);
9+
10+
intindex1 =len1 -1;
11+
intindex2 =len2 -1;
12+
13+
StringBuilderbld =newStringBuilder();
14+
booleancarry =false;
15+
16+
while((index1 >=0) || (index2 >=0) ||carry) {
17+
charc1 = (index1 >=0) ?a.charAt(index1) :'0';
18+
charc2 = (index2 >=0) ?b.charAt(index2) :'0';
19+
20+
charsum;
21+
if((c1 =='0') && (c2 =='0')) {// Both zeros
22+
sum =carry ?'1' :'0';
23+
carry =false;
24+
}
25+
elseif((c1 =='1') && (c2 =='1')) {// Both ones
26+
sum =carry ?'1' :'0';
27+
carry =true;
28+
}
29+
else {// Any one with a one
30+
sum =carry ?'0' :'1';
31+
// carry will be forwarded
32+
}
33+
bld.append(sum);
34+
35+
index1--;
36+
index2--;
37+
}
38+
39+
returnbld.reverse().toString();
40+
}
41+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp