I was recently asked to increment an integer string in Javascript as part of an interview. I managed to do it, but my code was quite messy. What is a good algorithm for incrementing integer strings by 1 in Javascript (or any language)?
"1"=>"2"
"9"=>"10"
"-10"=>"-9"
"-1"=>"0"
"123456"=>"123457"
This is to prevent integer overflow, so obviously I cannot convert the string to an integer.
Whoever comes up with a solution, please test it with the following code (assuming your function is called inc
):
var s = '-1000';
for(var i = -999; i <= 999; i++) {
s = inc(s);
if(s !== i.toString())
throw [s, i];
}
To increment a character in a Python, we have to convert it into an integer and add 1 to it and then cast the resultant integer to char. We can achieve this using the builtin methods ord and chr.
The increment operator in C++ is ++. In fact, that's why C++ is called C++, because it is meant to be one better than C. Decrease the value of a variable by one. The decrement operator in C++ is --.
Integer objects are immutable, so you cannot modify the value once they have been created. You will need to create a new Integer and replace the existing one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With