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

Commit46bf021

Browse files
committed
atoi
1 parent64f46bd commit46bf021

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎string/Atoi.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
packageAlgorithms.string;
2+
3+
publicclassAtoi {
4+
publicintatoi(Stringstr) {
5+
if (str ==null) {
6+
return0;
7+
}
8+
9+
// remove the spaces in the beginning and the end.
10+
Strings =str.trim();
11+
12+
booleanminus =false;
13+
longnum =0;
14+
for (inti =0;i <s.length();i++) {
15+
/*
16+
takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
17+
*/
18+
if (i ==0 &&s.charAt(i) =='+') {
19+
continue;
20+
}elseif (i ==0 &&s.charAt(i) =='-'){
21+
// get the
22+
minus =true;
23+
continue;
24+
}
25+
26+
intc =s.charAt(i) -'0';
27+
if (c >9 ||c <0) {
28+
// invalid character.
29+
break;
30+
}
31+
32+
num =num *10 +c;
33+
}
34+
35+
// If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is // returned.
36+
if (minus) {
37+
num = -num;
38+
num =Math.max(num,Integer.MIN_VALUE);
39+
}else {
40+
num =Math.min(num,Integer.MAX_VALUE);
41+
}
42+
43+
return (int)num;
44+
}
45+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp