FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/Maths/ParseInteger.java at master · coder2hacker/Java · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
coder2hacker
/
Java
Public
forked from
TheAlgorithms/Java
Notifications
You must be signed in to change notification settings
Fork
0
Star
2
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
Maths
/
ParseInteger.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
33 lines (31 loc) · 1.07 KB
Breadcrumbs
Java
/
Maths
/
ParseInteger.java
Copy path
File metadata and controls
33 lines (31 loc) · 1.07 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package
Maths
;
public
class
ParseInteger
{
public
static
void
main
(
String
[]
args
) {
assert
parseInt
(
"123"
) ==
Integer
.
parseInt
(
"123"
);
assert
parseInt
(
"-123"
) ==
Integer
.
parseInt
(
"-123"
);
assert
parseInt
(
"0123"
) ==
Integer
.
parseInt
(
"0123"
);
assert
parseInt
(
"+123"
) ==
Integer
.
parseInt
(
"+123"
);
}
/**
* Parse a string to integer
*
* @param s the string
* @return the integer value represented by the argument in decimal.
* @throws NumberFormatException if the {@code string} does not contain a parsable integer.
*/
public
static
int
parseInt
(
String
s
) {
if
(
s
==
null
||
s
.
length
() ==
0
) {
throw
new
NumberFormatException
(
"null"
);
}
boolean
isNegative
=
s
.
charAt
(
0
) ==
'-'
;
boolean
isPositive
=
s
.
charAt
(
0
) ==
'+'
;
int
number
=
0
;
for
(
int
i
=
isNegative
?
1
:
isPositive
?
1
:
0
,
length
=
s
.
length
();
i
<
length
; ++
i
) {
if
(!
Character
.
isDigit
(
s
.
charAt
(
i
))) {
throw
new
NumberFormatException
(
"s="
+
s
);
}
number
=
number
*
10
+
s
.
charAt
(
i
) -
'0'
;
}
return
isNegative
? -
number
:
number
;
}
}
Back
|
FazBrowse Home
|
New Git URL