7 kyu
String to integer conversion
2,056 of 4,481Uraza
Loading description...
Strings
Regular Expressions
Fundamentals
View
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Spoiler
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}
-
-
Your rendered github-flavored markdown will appear here.
-
Label this discussion...
-
No Label
Keep the comment unlabeled if none of the below applies.
-
Issue
Use the issue label when reporting problems with the kata.
Be sure to explain the problem clearly and include the steps to reproduce. -
Suggestion
Use the suggestion label if you have feedback on how this kata can be improved.
-
Question
Use the question label if you have questions and/or need help solving the kata.
Don't forget to mention the language you're using, and mark as having spoiler if you include your solution.
-
No Label
- Cancel
Commenting is not allowed on this discussion
You cannot view this solution
There is no solution to show
Please sign in or sign up to leave a comment.
11 should equal 'NaN' 123 should equal 'NaN' there is assertion errors for python
Your solution returns wrong answer for strings like
"1 2 3"
.Your solution has a bug, it's not a kata issue.
CS:
No random tests
mocha + chai
should be usedTest.expect
should be abortedJS:
No random tests
mocha + chai
should be usedTest.expect
should be abortedNo random tests in Ruby
No random test in Python.
Ruby 3.0 should be enabled, see this to learn how to do it
Enabled in this fork
🤮🤮🤮 🤮🤮🤮 🤮🤮🤮
Don't you mean possibly ?
Thanks for pointing that out, the text is fixed.
I am unable to pass 7th and 8th test in "should return NaN for non-integer strings" (ruby). What's in them?
what is 5th test in "should return NaN for non-integer strings"?
It's a hex value. You should print the input if you want to know any of the test cases.
how can i do this?
It depends on what language you're using, but all you have to do is output the variable that is given to you to the console.
Thanks
This comment has been hidden.
The error is because parseInt returns the first digit sequence and casts it into an integer.
str.match
will return an array of matches. Whenstr="16.5"
your output is ["1", "6", ".", "5"], then parseInt will look at the first value of the list and since it's a digit, it will return this into a integer. The final output is 1, which is not NaN and the program will return false.This case is similar when
str="5 friends"
since it will find the "5" in the string, return it as an array, then cast it into an integer.You need to make your code reject floating point values and any other string that contains alphabetical characters.
Thanks for your reply, I understood where the problem is occuring and that is why i'm looking if you can help me in guiding how we can reject/negate the floating point values. For the alphabetical order to be rejected i used \W. Please let me know what change i can include in my current regExp.Also do i have to use some other method rather than match() ?
Thanks once again.
Well first you need to test whether the given input string is a valid - it is valid if it's all digits and whitespace. If it is valid then return the integer conversion of the string, if not return NaN. This way is the best because it filters out the real results which can therefore be casted into an integer.
I would suggest not using match (use
test
instead) because it's not a good indication of whether the string can be an integer or not. As you can see, it extracts digits from string and will fail if there are alphabetical characters.AcesOfGlory, thanks for your answer! It's clear. But how the number would be formed?
Big thanks!
01 01 => 101 algo
01 01 => 1 algo
01 012 => 12
"1 algo" solution working fine but crashes with <NoMethodError: undefined method `each_with_index' on codewars
I don't understand your original question, but if you're asking about what form the input is in, you should print the input to the console to see examples. By using
puts(string)
you can see you get input with trailing spaces ("0 "), leading spaces (" 0") and spaces in between numbers ("0 0"). Only the first two should be valid since if you use .to_i and put in these values, you get the correct value.Your first algorithm doesn't work since it validates all inputs with spaces in, due to leading and trailing spaces being allowed. However your solution fails to take into account spaces inbetween the numbers. Spaces between numbers such as "1 2 3" should be invalid (return "NaN") and not return "123" because that is not have casting between string and integers work.
If you want to make your first solution work, remove the space from the characters disallowed and add .strip to string. You will want to do this because .strip will automatically remove trailing and leading spaces from the string (since they are allowed - to differentitate between leading/trailing and inbetween spaces) and will invalidate anything with a space between the numbers.
This comment has been hidden.
It fails when str = 123~~. Use Number() instead of parseInt().
Damn, it's actually working now. Thanks.
No problem, http://stackoverflow.com/questions/4564158/what-is-the-difference-between-parseintstring-and-numberstring-in-javascript if you want more information.
Very good for learning about regex within if
Hi, I would like to ask, what is right solution with last test case, I can't get it right even if output is 16.5 (and test case is "16.5") . What am I doing wrong, or what I get wrong from description? : )
Oh, I figure it out, it shoud take only integers, I missed first thousand times :D
Still having something wrong I do not have a clue what it is :D Please can someone help? :)
Post your code down below ^^
function myParseInt(IsItAInt) { if(isNaN(IsItAInt) || (IsItAInt % 1)){ var x = "NaN"; console.log(x); return x; } else{ var number = +IsItAInt; console.log(number); return number; } }
It fails when x = "1.0" and when x = "0x10"
It fails for "1.0" because the number is a floating type number and the task requires you to only accept integers. Even though the number has no fractional part, it is still a floating point number. You need to make your code so that it only accepts integers and no floating point numbers and will return "NaN" for the floats. Description states
It should make the conversion if the given string only contains a single integer value
It fails for "0x10" because your code automatically complier the number from base 10 (decimal) to base 16 (hexadecimal). You need to make your code return "NaN" for bases other than decimal. Description states
It should assume that all numbers are not signed and written in base 10
If you're lazy, you can just make special cases for them using an if statement to filter them out :P.
Oh, thank you! I get it now, I was also thinking that there could be some max range for int. values, but this is not the case :).
I have to try it again : )
All cases pass except for the following. From my understanding these should indeed return the number, rather than NaN. (because new lines and spaces are OK). Am I missing something??? [ '1', ' ', '1' ] Value is not what was expected [ '1', ' ', '2', ' ', '3' ]
The conversion should only be done when there is a single value.
And spaces can only be ignored at both ends.
When I press the submit button I get an "unknown error" this happens on IE
It is not clear what is meant by "should parse number starting with properly"
Shows up when you submit.
Once again pass all but one returns 'Value is not what was expected' says I pass 114 with one Failed.
I cannot see your solution so it is hard to help you.
This comment has been hidden.
Your code is not correct: like I mentioned earlier, you should print the test input (
console.log(str)
at the beginning of the test) and you will see which one is failing.In your case, add this line to the example test cases and rework your code until it passes:
Test.expect(isNaN(myParseInt("16.0")));
.I hope this helps.
Your code is not correct: like I mentioned earlier, you should print the test input (
console.log(str)
at the beginning of the test) and you will see which one is failing.In your case, add this line to the example test cases and rework your code until it passes:
Test.expect(isNaN(myParseInt("16.0")));
.I hope this helps.
Passing all but one test (114 of 115), would be great if i knew what the string was;
Can't you print the string at the beginning of your solution? Traces should also appear when submitting the code.
This comment has been hidden.
This comment has been hidden.
Hi. You can try your code with a "round" floating point number e.g.
12.0
: it should returnNaN
.This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
You can print the inputs when running the tests, this will help you fix your code.
description shows this: parseInt("10 apples") also returns 10 one of the tests: Test.assert_equals(my_parse_int("5 friends"),"NaN")
???????? huh
Try to read the description again.
oops! my bad (upvoted the kata)
No problem, have fun! :)
This comment has been hidden.
You should print the inputs when submitting using
console.log
: this should allow you to find out which input breaks your code.Thanks a lot.I shall try again.
This comment has been hidden.
Your solution returns
16
for the last example test case (myParseInt("16.5")
) while it should returnNaN
.Thanks a lot.I shall try again.
This comment has been hidden.
The Javascript test fixture lacks random tests; remember to keep random tests in mind when making future Kata :)
Any idea what this failure "None should equal 0" means ? What's the test case?
You're probably not returning anything, are you printing 'NaN' instead?
1 test not passed -_-
This comment has been hidden.
There are 109 test cases and not 105, try to print the input for the one that is failing.
Thank you. Helped me to solve this one! :)
It shold be written in the description that octal numbers will also be consider as NaN since in one of the test it is expected 0x10 to be Nan whereas it is actually a integer.
My code (python) is throwing up the error: 11 should equal NaN
I thought it might be that I needed to ensure that the string argument actualy had type 'str' before parsing, but that didn't seem to work. Any ideas? This is for the blind test cases under the heading "should return NaN for non-integer strings." Thanks
To clarify, my code currently outputs "NaN" for input 11, and 11 for input "11"
One of the test case expecting "NaN" as an output is "1 1" (with a whitespace between the two 1), perhaps that is the one your code is failing one.
This is a minor issue, but in the python version, it wants
"NaN"
as a string, not literallynan
(which you can return withfloat('nan')
. This should be specified.The code template clearly states to return
"NaN"
as a string and the example tests confirm that, but if you find it to be insufficient and the author is ok with it, I can add that to the description too :)In general, I would say that user-editable spaces like the code template are not the appropriate place for instructions; doubly so for the example tests, since those tests can be modified but are not restored by the reset button.
In this specific case, the instructions are inaccurate and should be fixed.
"NaN"
is a string,NaN
is not (and in fact,NaN
does not exist in Python, thoughnan
does, sort of).Hi, the description of the Python version has been updated to make it clear that a string is expected.
Thanks for the feedback.
Translated again into both Python and Ruby; I say in the template to return "NaN" as a string, but let me know if you might appreciate me to update the description a bit :)
It looks clear to me, thanks for the translations! :)
Description doesn't makes its clear for getting NaN in case of '1 2 3'
Thanks for the feedback, the kata description has been updated.
it wasn't clear about all the tests that would be ran. I passed the examples but kept failing on one actual test, and I have no idea what it was testing for.
Thanks for the feedback.
The idea is also to have people write their own tests.
In case the indications are not sufficient, you can always print the input given to your method for the failing test.
oh man, so sorry about this comment, it was my first kata and I totally get it now. thank you!
how do you print the input for the failed test? I have 2 test failed and 113 passed. I dont know why it failed
You can print the input string
str
to the console.Some of the test cases also contain whitespaces or characters such as
\t
and\n
at the beginning and end of the string so you will not actually see them when printing the input.Sorry if I am asking a stupid question, but how do I print the input string to the console? All I see in the console are "Test Passed" or "Value is not what was expected" statements when I try to use a console.log method.
Try using
console.log
.I passed the challenge by beating two of the most difficult test cases - if you add a few more letters/add more strange characters to the NaN test case, I think that would prevent people from simply beating the test case and coming up with the desired answer.
Is not clear that only numbers with space between them have to be NaN result
Are you referring to an input string that would contain several valid values like
"1 2 3"
?Yes!
The kata's description has been rephrased like this: "It should make the conversion if the given string only contains a single integer value". Hopefully it is clearer.
Thanks for the feedback! :)
CoffeeScript translation published.
Great, thanks!
This comment has been hidden.
Thanks for your valuable feedback, the test cases have been updated.
I consider
"\t123\t"
as a valid input: spaces, tabs, line feeds... are valid "spaces" for this kata.Is a "+" or "-" allowed before a number? Whatever the answer is, a test like
"+1"
would fail some solutions.It was not directly clear for me that floats need to be returned as NaN. Only after the provided test with a float failed I noticed that I need to return NaN.
Thanks for the feedback, the description has been updated.
There's a typo in the example test fixture, saying
IsNaN
instead ofisNaN
, which produces an error.Thanks, this is fixed.