-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathString2Long.java
More file actions
50 lines (40 loc) · 1.05 KB
/
Copy pathString2Long.java
File metadata and controls
50 lines (40 loc) · 1.05 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main;
public class String2Long {
public long stringToLong(String s) {
if (null == s) {
throw new IllegalArgumentException("Null string.");
}
int len = s.length();
boolean isNagtive = false;
if(0 == len) {
throw new IllegalArgumentException("Empty string.");
}
//Get the first character and check the sign
if(s.charAt(0) == '-')
{
s = s.substring(1);
isNagtive = true;
}
else if(s.charAt(0) == '+')
{
s = s.substring(1);
}
//try to convert the rest of string to long
//define result as long to make sure it won't overflow
long result = 0;
for (int i = 0; i < s.length(); i++)
{
int value = s.charAt(i) - '0';
//check the invalid character
if(value < 0 || value > 9)
throw new NumberFormatException("Invalid string.");
result *= 10;
//check the Overflow case
if(result > Long.MAX_VALUE)
throw new NumberFormatException("Number Overflow.");
result += value;
}
//covert the result to long based on sign
return (isNagtive ? -1 : 1) * (long) result;
}
}