前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#版 - Leetcode 65. 有效数字 - 题解

C#版 - Leetcode 65. 有效数字 - 题解

作者头像
Enjoy233
发布2019-03-05 15:47:50
6190
发布2019-03-05 15:47:50
举报

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: C++函数的形式已经更新了。如果你仍然看见你的函数接收 const char *类型的参数,请点击重载按钮重置你的代码。



思路:

按照题意,满足要求的数形如: ☐ ±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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年07月09日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Leetcode 65. 有效数字
  • 题目描述
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档