user110269
user110269

Reputation: 25

How can I know if a number is contained in another in java?

How can I know if a number is contained in another in java without converting to string? for example, if i put 123456 and 234 i should print true, but if i put 678 and 34 it should print false.

Upvotes: 1

Views: 751

Answers (2)

Nowhere Man
Nowhere Man

Reputation: 19555

The algorithm to find if a contains b could be as follows:

  1. Find the power of 10 p closest to b to review the last digits of a using modulo operation.
  2. While a >= b, check if the remainder of a % p or a are equal to b; if not, divide a by 10 (decimal right shift):
static boolean aContainsB(int a, int b) {
    a = Math.abs(a);
    b = Math.abs(b);
    int p = 1;
    while (p <= b) {
        p *= 10;
    }
    
    boolean contains = a == b;
    while (!contains && a >= b) {
        contains = a % p == b || a == b;
        a /= 10;
    }
    return contains;
}

Tests and output:

int[][] tests = {
    {234, 234}, {123, 234}, {123, 23}, {1234, 23}, {12345, 12},
    {325, 1}, {210, 1}, {123, 1}, {211, 1}, {210, 10},
    {91019, 10}
};

for (int[] t : tests) {
    System.out.printf("%d contains %d ? %s%n", t[0], t[1], aContainsB(t[0], t[1]));
}

Output

234 contains 234 ? true
123 contains 234 ? false
123 contains 23 ? true
1234 contains 23 ? true
12345 contains 12 ? true
325 contains 1 ? false
210 contains 1 ? true
123 contains 1 ? true
211 contains 1 ? true
210 contains 10 ? true
91019 contains 10 ? true

Upvotes: 2

fr3ddie
fr3ddie

Reputation: 406

If you are masochist, you can put your string of number into List/Table (one number to one indexed cell using for loop) and implement contains() method like for String objects.
But better and easier way is convert int to String and use String's `contains()'.

int a = 123456;
boolean contains = String.valueOf(a).contains("234");

Why do you don't want to convert to String?

Upvotes: 0

Related Questions