java - Calling for even and odd figures -


write method named hasanodddigit returns whether digit of positive integer odd. method should return true if number has @ least 1 odd digit , false if none of digits odd. 0, 2, 4, 6, , 8 digits, , 1, 3, 5, 7, 9 odd digits.

for example, here calls method , expected results:

call value returned hasanodddigit(4822116) true hasanodddigit(2448) false hasanodddigit(-7004) true should not use string solve problem.

this attempt @ question:

public boolean hasanodddigit(int num){ int number=0;  while (number > 0) {     number= number % 10;     number = number / 10; }     if(number%2==0 && num%2==0){         return false;     }else{          return true;     }   } 

called hasanodddigit(4822116) , gives me false instead of true.

your method should check each digit goes through loop, rather waiting loop complete before making decision. currently, while loop runs number down zero, , tries check value. naturally, time loop over, both values zero, return false.

public boolean hasanodddigit(int num){     // not need make copy of num, because     // of pass-by-value semantic: since num copy,     // can change inside method see fit.     while (num > 0) {         int digit = num % 10;         if (digit % 2 == 1) return true;         num /= 10;     }     // if made through loop without hitting odd digit,     // digits must     return false; } 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -