Home > Enterprise >  I need a function in java where it counts odd or even digits in a specific number and i can choose i
I need a function in java where it counts odd or even digits in a specific number and i can choose i

Time:11-27

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;
}

`

CodePudding user response:

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

CodePudding user response:

You could try something like this

final int EVEN = 0;
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));
}
  •  Tags:  
  • java
  • Related