java - Comparing integers and creating the smallest integer possible from the digits of the given integers -
i need write following method: accepts 2 integer parameters , returns integer. if either integer not 4 digit number method should return smaller integer. otherwise, method should return 4 digit integer made of smallest digit in thousands place, hundreds place, tens place , ones place. cannot turn integers strings, or use lists, or arrays.
for example biggestloser(6712,1234) returns 1212 example biggestloser(19,8918) returns 19
here's how i've started write it:
public static int biggestloser(int a, int b){ if(a<9999 || b<9999){ if(a<b) return a; else if(b<a) return b; } int at=a/1000; int ah=a%1000/100; int an=a%100/10; int ae=a%10; int bt=b/1000; int bh=b%1000/100; int bn=b%100/10; int be=a%10; if(at<bt && ah<bh && an<bn && ae<be) return at*1000+ah*100+an*10+ae; else if(at<bt && ah<bh && an<bn && be<ae) return at*1000+ah*100+an*10+be; else if(at<bt&& ah<bh && bn<an && ae<be) else return at*1000+ah*100+bn*10+ae;
however, looks i'm going have write way many if statements, there shorter way write code?
public static int biggestloser(int a, int b) { if (a < 1000 || >= 10000 || b < 1000 || b >= 10000) { return math.min(a, b); } else { // both , b 4 digits int result = 0 ; int multiplier = 1 ; (int digit = 0; digit < 4; digit++) { int nextdigit = math.min(a % 10, b % 10); result = result + nextdigit * multiplier ; multiplier = multiplier * 10 ; = / 10 ; b = b / 10 ; } return result ; } }
how work? a % 10
remainder when a
divided 10
: in other words least significant digit of a
(the "ones place").
a = / 10
performs integer division, divides a
10
, ignores fraction. 1234
becomes 123
, , on next iteration 123
becomes 12
, etc. in other words, discards "ones place".
so first time through loop, @ "ones" a
, b
, find smallest one, , add result
. drop "ones" both a
, b
. used "tens" "ones". second time through loop, smallest "ones" again: smallest "tens". want add result
, need multiply 10
. multiplier
: each time through loop multiplier multiplied 10
. each time, smallest "ones", multiply correct thing, add result, , drop "ones" a
, b
.
just fun, here's implementation needs 1 statement (and works if replace "four digits" positive number of digits). can ask instructor explain ;).
public static final int num_digits = 4 ; public static final int max = (int) math.pow(10, num_digits) ; public static final int min = max / 10 ; public static int biggestloser(int a, int b) { return (a < min || >= max || b < min || b >= max) ? math.min(a, b) : intstream.iterate(1, multiplier -> multiplier * 10).limit(num_digits) .map(multiplier -> math.min((a / multiplier) % 10, (b / multiplier) % 10) * multiplier ) .sum(); }
Comments
Post a Comment