[LeetCode] Valid Number

來源:互聯網
上載者:User

標籤:

I guess some of you may have noticed that this seemingly simple problem has the lowest acceptance rate among all problems on the LeetCode OJ. Well, some of you may also complain about the annoying large number of special cases and have no idea of how to handle them systematically. Well, this link provides a nicely systematic idea, which gives a very clean and clear code. Take a look at it and you will become happy with this problem :-)

The code is rewritten as follows.

 1 class Solution { 2 public: 3     bool isNumber(string s) { 4         int i = 0, n = s.length(); 5         // Skip the leading spaces 6         while (i < n && isspace(s[i])) i++; 7         // Skip the sign 8         if (s[i] == ‘+‘ || s[i] == ‘-‘) i++; 9         // Check for the following significant parts10         int digits = 0, dots = 0;11         while (i < n && (isdigit(s[i]) || s[i] == ‘.‘)) {12             if (isdigit(s[i])) digits++;13             else dots++;14             i++;15         }16         if (digits < 1 || dots > 1) return false;17         if (i == n) return true;18         // Check for the exponential parts19         if (s[i] == ‘e‘) {20             i++;21             if (i == n) return false;22             if (s[i] == ‘+‘ || s[i] == ‘-‘) i++;23             digits = 0;24             while (i < n && (isdigit(s[i]))) {25                 digits++;26                 i++;27             }28             if (digits < 1) return false;29         }30         // Skip the trailing spaces31         while (i < n && isspace(s[i])) i++;32         return i == n;33     }34 };

 

[LeetCode] Valid Number

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.