• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Valid Number

leetcode里最恶心的题目。。面试问这种题目可以去撞墙了。。

 自己写了一遍

 1 class Solution {
 2 public:
 3     bool isNumber(const char *s) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         while (isspace(*s)) s++;
 7         if (*s == '+' || *s == '-') s++;
 8         bool space, e, dot, first, second;
 9         space = e = dot = first = second = false;
10         while (*s != '\0') {
11             if (*s == '.') {
12                 if (e || space || dot || second) return false;
13                 dot = true;
14             }
15             else if (*s == 'e') {
16                 if (e || space || !first) return false;
17                 e = true;
18             }
19             else if (isdigit(*s)) {
20                 if (space) return false;
21                 if (!e) first = true;
22                 else second = true;
23             }
24             else if (isspace(*s)) space = true;
25             else if (*s == '+' || *s == '-') {
26                 if (space || *(s-1) != 'e') return false;
27             }
28             else return false;
29             s++;
30         }
31         if (!first) return false;
32         if (e && !second) return false;
33         return true;
34     }
35 };

 C#

 1 public class Solution {
 2     public bool IsNumber(string s) {
 3         int cur = 0;
 4         while (cur < s.Length && s[cur] == ' ') cur++;
 5         if (cur < s.Length && (s[cur] == '+' || s[cur] == '-')) cur++;
 6         bool space, e, dot, first, second;
 7         space = e = dot = first = second = false;
 8         while (cur < s.Length) {
 9             if (s[cur] == '.') {
10                 if (e || space || dot || second) return false;
11                 dot = true;
12             }
13             else if (s[cur] == 'e') {
14                 if (e || space || !first) return false;
15                 e = true;
16             }
17             else if (s[cur] >= '0' && s[cur] <= '9') {
18                 if (space) return false;
19                 if (!e) first = true;
20                 else second = true;
21             }
22             else if (s[cur] == ' ') space = true;
23             else if (s[cur] == '+' || s[cur] == '-') {
24                 if (space || (cur > 0 && s[cur-1] != 'e')) return false;
25             }
26             else return false;
27             cur++;
28         }
29         if (!first) return false;
30         if (e && !second) return false;
31         return true;
32     }
33 }
View Code

 

posted @ 2013-04-22 13:29  ying_vincent  阅读(330)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3