-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution65.cs
66 lines (57 loc) · 1.65 KB
/
Solution65.cs
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
namespace LeetCode.Solutions;
public class Solution65
{
/// <summary>
/// 65. Valid Number - Hard
/// <a href="https://leetcode.com/problems/valid-number">See the problem</a>
/// </summary>
public bool IsNumber(string s)
{
var i = 0;
var n = s.Length;
var isNumeric = false;
// Trim leading and trailing spaces
s = s.Trim();
// Check for optional sign
if (i < n && (s[i] == '+' || s[i] == '-'))
{
i++;
}
// Check for digits before the dot
while (i < n && char.IsDigit(s[i]))
{
i++;
isNumeric = true;
}
// Check if there is a dot and digits after
if (i < n && s[i] == '.')
{
i++; // Skip the dot
// It's still valid if there are digits after the dot
while (i < n && char.IsDigit(s[i]))
{
i++;
isNumeric = true;
}
}
// Check for exponent part
if (isNumeric && i < n && (s[i] == 'e' || s[i] == 'E'))
{
i++; // Skip 'e' or 'E'
isNumeric = false; // Reset for exponent validation
// Optional sign in exponent
if (i < n && (s[i] == '+' || s[i] == '-'))
{
i++;
}
// Check digits in exponent
while (i < n && char.IsDigit(s[i]))
{
i++;
isNumeric = true;
}
}
// Ensure the whole string is processed and a number is present
return isNumeric && i == n;
}
}