版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址
http://blog.csdn.net/lzuacm

Leetcode 65. 有效数字

Leetcode 65. Valid Number

在线提交:
Leetcode https://leetcode.com/problems/valid-number/

类似问题 - PAT 1014_牛客网
https://www.nowcoder.com/pat/6/problem/4050


题目描述

验证给定的字符串是否为数字(科学计数法)。

例如:
“0” => true
” 0.1 ” => true
“abc” => false
“1 a” => false
“2e10” => true

说明: 我们有意将问题陈述地比较模糊。在实现代码之前,你应当事先思考所有可能的情况。

更新于 2015-02-10:
<kbd>C++</kbd>函数的形式已经更新了。如果你仍然看见你的函数接收 <kbd>const char *</kbd>类型的参数,请点击重载按钮重置你的代码。


  ●  题目难度: Hard

思路:

按照题意,满足要求的数形如: ☐ ±4.36e±05☐ ,其中☐表示首尾的若干个连续的空格。

可更具体地表示为:☐ ±double e±0…0int+☐ (当然此处的int是long long的, 或int64的,而0…0是若干个连续的0)。而对于特例”0e”,该串中e后为空串,应返回false。事实上 ±double可以直接看作double,±0…0int可直接看作int。

需测试的Test Case:

"0e-1"
"0"
" 0.1 " 
"abc"
"1 a" 
" 2e10 "
"+ 1"
"5e001"
"44e016912630333"
"2e0"
"2e00"
"0e"
" +4.36e-01"

Expected answer:

true
true
true
false
false
true
false
true
true
true
true
false
true

已AC代码:

public class Solution
{
    public bool IsNumber(string s)
    {
        s = s.Trim();
        string[] arr = s.Split('e');
        // var hasSign = arr[0].IndexOf("+", StringComparison.Ordinal) == 0 || arr[0].IndexOf("-", StringComparison.Ordinal) == 0;
        // string newPart1 = hasSign ? arr[0].Substring(1) : arr[0];
        string newPart1 = arr[0];
        if (newPart1.IndexOf(" ", StringComparison.Ordinal) >= 0)
            return false;
        bool isPart1Double = double.TryParse(newPart1, out var part1);
        string newPart2 = arr.ElementAtOrDefault(1);
        if (newPart2 == String.Empty) // handle test case like: "0e"
            return false;

        if (newPart2 != null)
        {
            foreach (char ch in newPart2)
            {
                if (ch == '0')
                    newPart2 = newPart2.Substring(1);
            }
        }

        bool isPart2Int = Int64.TryParse(newPart2, out var part2);
        if (arr.Length == 1)
        {
            if (isPart1Double)
                return true;
        }

        if (arr.Length == 2)
        {
            if (isPart1Double && newPart2 == String.Empty)
                return true;
            if (isPart1Double && isPart2Int)
                return true;
        }

        return false;
    }
}

Rank:
You are here! Your runtime beats 69.44% of csharp submissions.
1481 / 1481 test cases passed.
Runtime: 96 ms