2

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?

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
jeffkmeng
  • 851
  • 1
  • 8
  • 30

2 Answers2

7

% 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))

keyhan
  • 247
  • 1
  • 6
  • 1
    Smart but it'd be better if you explained how to get the values for *modulation and division* for any given number and for any position we want to clear. – Taslim Oseni Jan 05 '18 at 17:27
1

This will remove only one digit:

public static int RemoveNthPosition(int input, int position) {
    int leftDivider = (int) Math.pow(10.0, position);
    int rightDivider = (int) Math.pow(10.0, position - 1);

    int leftSide = input / leftDivider;
    int rightSide = input % rightDivider;

    return leftSide * rightDivider + rightSide;
}

To remove multiple at the same time:

public static int RemoveMultiplePositions(int input, int[] positions) {
    Arrays.sort(positions);
    int result = input;
    for (int count = 0; count < positions.length; count++) {
        result = RemoveNthPosition(result, positions[count] - count);
    }

    return result;
}

In your case, it would be:

System.out.println(RemoveMultiplePositions(987654321, new int[] { 3, 4 }));
z m
  • 1,493
  • 2
  • 19
  • 21