-
Notifications
You must be signed in to change notification settings - Fork 41
/
65.swift
145 lines (119 loc) · 3.5 KB
/
65.swift
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
//
// ValidNumberTest.swift
// LeetCode
//
// Created by Lex Tang on 5/5/15.
// Copyright (c) 2015 Lex Tang. All rights reserved.
//
/*
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
@see also: https://github.com/haoel/leetcode/blob/master/algorithms/validNumber/validNumber.cpp
*/
import Foundation
import XCTest
extension String {
func isNumber() -> Bool {
if isEmpty {
return false
}
var index = 0
let length = self.count
for (i, c) in self.enumerated() {
if c.isSpace() {
continue
} else {
if i != length - 1 {
index = i
}
break
}
}
if index == length - 1 {
return false
}
if let c = self[index + 1] {
if c == "+" || c == "-" {
index += 1
}
}
var hasPoint = false
var hasE = false
var s = self[index]
let firstDigit = s
while index < length {
defer { index += 1 }
s = self[index]
if s == "." {
if hasPoint || hasE {
return false
}
if s == firstDigit && self[index + 1] != nil && !self[index + 1]!.isDigit() {
return false
}
hasPoint = true
continue
}
if s == "e" {
if hasE || s == firstDigit {
return false
}
index += 1
s = self[index]
if s == "+" || s == "-" {
index += 1
}
s = self[index]
if s == nil || !s!.isDigit() {
return false
}
hasE = true
continue
}
if s != nil && s!.isSpace() {
while index < length {
s = self[index]
if s != nil && !s!.isSpace() {
return false
}
index += 1
}
return true
}
if s != nil && !s!.isDigit() {
return false
}
}
return true
}
}
class ValidNumberTest: XCTestCase {
func testValidNumber() {
XCTAssertTrue("1.044".isNumber(), "")
XCTAssertTrue(" 1.044 ".isNumber(), "")
XCTAssertTrue(!"1.a".isNumber(), "")
XCTAssertTrue(!"abc".isNumber(), "")
XCTAssertTrue(!"e".isNumber(), "")
XCTAssertTrue(!"1e".isNumber(), "")
XCTAssertTrue("1e2".isNumber(), "")
XCTAssertTrue(!"".isNumber(), "")
XCTAssertTrue(!" ".isNumber(), "")
XCTAssertTrue("1.".isNumber(), "")
XCTAssertTrue(".2".isNumber(), "")
XCTAssertTrue(!" . ".isNumber(), "")
XCTAssertTrue(!".".isNumber(), "")
XCTAssertTrue(!"1.2.3".isNumber(), "")
XCTAssertTrue(!"1e2e3".isNumber(), "")
XCTAssertTrue(!"1..".isNumber(), "")
XCTAssertTrue(!"+1.".isNumber(), "")
XCTAssertTrue(!" -1.".isNumber(), "")
XCTAssertTrue(!"6e6.5".isNumber(), "")
XCTAssertTrue("005047e+6".isNumber(), "")
}
}