3 ms·
You do realize it returns 1 for an empty string right? I mean it doesn't have any digits in it... What about adding a check of str[0] == 0 -> return 0 Also,
by pvtmert 5y ago
You do realize it returns 1 for an empty string right?
I mean it doesn't have any digits in it...
What about adding a check of str[0] == 0 -> return 0
Also, giving char str[] will make it char* str.
Which can be null. This may cause reading a random memory location (possibly segfault or use-after-free)
edit: I get the comments but empty string still contains no digits. Given the regex would be ^[0-9]+ (+ instead of *)
What I want to say is string has a numerical value or not. Empty string is NaN.
- zeven7 5y agoEmpty string contains no non-digits. Therefore it is only digits.
- Someone 5y ago“contains only digits” isn’t synonymous with “not (doesn’t have any digits)” It is synonymous with “none of the characters is a non-digit”, which is true for the empty string.
- Stratoscope 5y ago> You do realize it returns 1 for an empty string right? I mean it doesn't have any digits in it... Yes, and that was deliberate on my part, as it meets my expectation of what such a function should do in this edge case. The problem statement was "Set boolean b to true if string s contains only characters in range '0'..'9', false otherwise." To my mind, the question "is every character in the string a digit" should be equivalent to "are there any non-digits in the string" (with the answer inverted, of course). Returning 0 (false) for the empty string makes those questions not equivalent. It makes the empty string a special case. Of course the real problem is that the problem is under-specified. It should call out specifically what should happen for an empty string, because as illustrated here, this is something where reasonable people may disagree. > Also giving char str[] will make it char* str. Which can be null. This may cause reading a random memory location (possibly segfault or use-after-free) Well yes, of course. The point of my comment wasn't to write bullet-proof library-ready code, it was only to illustrate two things: code like this should always go in a function, and the entire task can be accomplished in a single pass through the string. Thanks for keeping me on my toes!
- anonymoushn 5y agoWhere did your choice of regex come from? The problem statement does not have any regex, and if you wanted to derive a regex from the problem statement you would probably need to get ^[0-9]*$ if you wanted to be correct.