-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathleetcode0065.go
68 lines (54 loc) · 1.01 KB
/
leetcode0065.go
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
LeetCode 65: https://leetcode.com/problems/valid-number/
*/
package leetcode
import "strings"
func isNumber(s string) bool {
s = strings.Trim(s, " ")
segs := strings.Split(s, "e")
if len(segs) > 2 {
return false
}
num := removeSign(segs[0])
if len(num) == 0 {
return false
}
if len(segs) == 2 {
exponent := removeSign(segs[1])
if len(exponent) == 0 || !isUnsignedDigits(exponent) {
return false
}
}
segs = strings.Split(num, ".")
if len(segs) > 2 {
return false
}
integer := segs[0]
if len(integer) > 0 && !isUnsignedDigits(integer) {
return false
}
if len(segs) == 2 {
float := segs[1]
if len(integer) == 0 && len(float) == 0 {
return false
}
if len(float) > 0 && !isUnsignedDigits(float) {
return false
}
}
return true
}
func removeSign(s string) string {
if len(s) > 0 && (s[0] == '+' || s[0] == '-') {
s = s[1:]
}
return s
}
func isUnsignedDigits(s string) bool {
for _, ch := range s {
if ch < '0' || ch > '9' {
return false
}
}
return true
}