optimization - Best way to check if there is a 0 in an integer -


what best way check if there's 0(zero) in integer

for example:

505 -> true 555 -> false 44444032 -> true 0000 -> true 

i have tried this

public bool has0(int no) {     if(no==0)return true;     while(no!=0)     {         if(no%10==0)return true;         no=no/10;     }     return false; } 

this works,but takes time specially on large numbers given fact need call method 1 billion times on large numbers

for(int i=0;i<1000000000;i++)has0(i); 

so,what best way check if 0 exist in number using bit level operators |,&,^ or other way.

thanks..

modulo expensive integer operation (similar integer divides). eliminate half of possible answers in test seeing if number even. no odd number has modulo 10 equal zero.

if (((no & 0x1) == 0x00) && ((no % 10) == 0)) return true;

you pay little more on numbers, lot less on odd ones. hence, if it's numbers, won't (it hurt), if it's 50/50 or 20/80 (20 percent odd), you'll still come out ahead.

also, integer multiply less expensive, may divide first , calculate modulo 10.

while (no) {   if (no & 0x1))  // odd?     no /= 10;   else  //   {     int nnext = no / 10;  // integer divide, , calculate modulo in next line     if ((no - (10 * nnext)) == 0)  // replaces "more expensive" modulo operation integer multiply , subtraction       return true;     no = nnext;   } } 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -