简体   繁体   中英

I need a function in java where it counts odd or even digits in a specific number and i can choose if i want the the odd or the even digits

taking for example i have two numbers JEAN: "5143436111" SAMI: "4501897654"

I need the funtion to give me this:

i have 7 odd digits in JEAN number i have 5 even digits in SAMI number

I tried this function but i want to choose if i want the odd or even digits bcz in here its showing both but i want my fuction to give me the choice to choose

`

static int countEvenOdd(int n)
{
    int even_count = 0;
    int odd_count = 0;
    while (n > 0)
    {
        int rem = n % 10;
        if (rem % 2 == 0)
            even_count++;
        else
            odd_count++;
        n = n / 10;
    }
    System.out.println ( "Even count : " +
                              even_`your text`count);
    System.out.println ( "Odd count : " +
                              odd_count);
    if (even_count % 2 == 0 &&
         odd_count % 2 != 0)
        return 1;
    else
        return 0;
}

`

You could try something like this

static final int EVEN = 0;
static final int ODD = 1;

static int count(int n, int remainder)
{
    int count = 0;
    while (n > 0)
    {
        int rem = n % 10;
        if (rem % 2 == remainder)
            count++;
        n = n / 10;
    }
    return count;
}

public static void main(String[] args) {
    System.out.println("Even Count: " + count(12233, EVEN));
    System.out.println("Odd Count: " + count(12233, ODD));
}

Appreciate that you really only need to compute the number of odd or even digits, since the other count can be inferred using the total number of digits in the input. You may use:

int countOdd(long n) {
    int count = 0;

    while (n > 0) {
        long rem = n % 10;
        if (rem % 2 == 1) ++count;
        n = n / 10;
    }
    return count;
}

long num = 5143436111L;
int odd = countOdd(num);
int even = (int) (Math.log10(num) + 1) - odd;
System.out.println(num + ", EVEN => " + even + ", ODD => " + odd);

This prints:

5143436111, EVEN => 3, ODD => 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM