java - Extracting even digits from int -
here problem solving.
write method evendigits accepts integer parameter n , returns integer formed removing odd digits n. following table shows several calls , expected return values:
call valued returned evendigits(8342116); 8426 evendigits(4109); 40 evendigits(8); 8 evendigits(-34512); -42 evendigits(-163505); -60 evendigits(3052); 2 evendigits(7010496); 46 evendigits(35179); 0 evendigits(5307); 0 evendigits(7); 0
if negative number digits other 0 passed method, result should negative, shown above when -34512 passed.
leading zeros in result should ignored , if there no digits other 0 in number, method should return 0, shown in last 3 outputs.
i have far -
public static int evendigits(int n) { if (n != 0) { int new_x = 0; int temp = 0; string subs = ""; string x_str = integer.tostring(n); if (x_str.substring(0, 1).equals("-")) { temp = integer.parseint(x_str.substring(0, 2)); subs = x_str.substring(2); } else { temp = integer.parseint(x_str.substring(0, 1)); subs = x_str.substring(1); } if (subs.length() != 0) { new_x = integer.parseint(x_str.substring(1)); } if (temp % 2 == 0) { return integer.parseint((integer.tostring(temp) + evendigits(new_x))); } else { return evendigits(new_x); } } return 0; }
why people seem want convert string
deal digits? java has arithmetic primitives handling job. example:
public static int evendigits(int n) { int rev = 0; int digitcount = 0; // handle negative arguments if (n < 0) return -evendigits(-n); // extract digits variable rev while (n != 0) { if (n % 2 == 0) { rev = rev * 10 + n % 10; digitcount += 1; } n /= 10; } // digits extracted in reverse order; reverse them again while (digitcount > 0) { n = n * 10 + rev % 10; rev /= 10; digitcount -= 1; } // result in n return n; }
although makes no difference simple academic exercise such one, handling job via arithmetic alone can expected perform better involving converting string
.
Comments
Post a Comment