Search code examples
javaintegerdigits

Remove nth digit from an integer without converting to string


Say I have this integer in java, 987654321. I want to be able to remove, say the third and fourth digits, so I can get 9876521 in java.

I know I can do this by converting to a string, then taking a substring, but is there a way to do this without converting to a string?


Solution

  • % and / are your friends here! Using modulus and division we can get pieces of the number that we want.

    We use modulus to eliminate the most significant digits, and division to eliminate the least significant digits. We can use division because the remainder gets truncated.

    Then we put the two pieces we got from these two operations together. However, we need to shift the digits we got from the division to have room for the least significant digits.

    Take 987654321 / 10000, this will give you 98765 (let's call this x)

    Take 987654321 % 100, this will give you 21 (let's call this y)

    x * 100 + y = 9876521.

    More generally, if you want to remove a to bth digits from the number n (where a < b),

    n % 10^(a-1) + ((n / 10^(b)) * 10^(a-1))