Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment an integer string

Tags:

javascript

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];
}
like image 972
Leo Jiang Avatar asked Feb 04 '15 22:02

Leo Jiang


People also ask

How do you increment an int to a string in Python?

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.

How do I increment a string in C++?

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 --.

Can you increment an integer in Java?

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.


1 Answers

  1. Split the string into substrings that are definitely small enough to increment properly.
  2. Increment/decrement the last chunk (based on the sign).
  3. Carry any overflow into the next chunk—or borrow from the next chunk—until done.
  4. Join the integers as strings again.
like image 200
Phrogz Avatar answered Oct 03 '22 03:10

Phrogz