8000 完成String转换long的函数。 · ssjssh/javaalgorithm@e26f9d7 · GitHub
[go: up one dir, main page]

Skip to content

Commit e26f9d7

Browse files
author
shengshijun
committed
完成String转换long的函数。
StringBuilder实现longValue函数。
1 parent 2125aab commit e26f9d7

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/main/java/ssj/algorithm/math/MathUtil.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,35 @@ public static int strToInt(String str) {
248248
return result;
249249
}
250250

251+
public static long strToLong(String str) {
252+
Preconditions.checkNotNull(str);
253+
Preconditions.checkArgument(str.length() > 0);
254+
Preconditions.checkArgument(!(str.length() == 1 && (str.charAt(0) == '+' || str.charAt(0) == '-')));
255+
long result = 0;
256+
boolean is_negative = false;
257+
int num_start = 0;
258+
if (str.charAt(0) == '-') {
259+
is_negative = true;
260+
num_start = 1;
261+
} else if (str.charAt(0) == '+') {
262+
num_start = 1;
263+
}
264+
265+
for (int i = num_start; i < str.length(); i++) {
266+
long this_digit = str.charAt(i) - '0';
267+
if (this_digit < 0 || this_digit > 9) {
268+
throw new ArithmeticException("wrong format");
269+
}
270+
result = Math.multiplyExact(result, 10L);
271+
if (is_negative) {
272+
result = Math.subtractExact(result, this_digit);
273+
} else {
274+
result = Math.addExact(result, this_digit);
275+
}
276+
}
277+
return result;
278+
}
279+
251280
public int closestBig(int origion) {
252281
Preconditions.checkArgument(origion > 0);
253282
int first_one_index = BitUtil.firstBitOne(origion);

src/main/java/ssj/algorithm/string/StringBuilder.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,10 @@ public int intValue() {
156156
return MathUtil.strToInt(toString());
157157
}
158158

159+
public long longValue() {
160+
return MathUtil.strToLong(toString());
161+
}
162+
159163
public double doubleValue() {
160164
//TODO 完成String to double
161165
return -1;

0 commit comments

Comments
 (0)
0