Wednesday, August 19, 2015

if string is integer

// examples
//true
1
+1
+01
-1
-01
+0
-0
+00
-00
12345678901234567890
-12345678901234567890

//false
+
-
++0
--0
null
""
"   "
(s):
    if s == null:
        return false
    s = s.trim()
    if s == "":
        return false
    for i = 0, i < s.length(), i++:
        if (s[i] == '+' || s[i] == '-') && i == 0 && i + 1 < s.length():
            continue
        digit = s[i] - '0'
        if !(0 <= digit <= 9):
            break
    return i == s.length()

No comments:

Post a Comment