This week's book giveaway is in the Kotlin forum.We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# multiplying ints

boyet silverio
Ranch Hand
Posts: 173
An interview question which went something like
public int multiply(int a, int b);
How can the method's body be implemented to get the correct product from multiplying 'a' with 'b', if 'a' and 'b' is given a value of nine hundred million and one billion, respectively?

Jason Menard
Sheriff
Posts: 6450
The method should be returning a long, not an int. Or is that the point?

Francis Siu
Ranch Hand
Posts: 867
The method should be returning a long, not an int. Or is that the point?

Michael Morris
Ranch Hand
Posts: 3451

Siu, you have a strange sense of humor. You need to lay off the chicken feet soup for a while.

boyet silverio
Ranch Hand
Posts: 173
yep, the method header's a constraint.

-------------------------------------
as someone said in the movie Matrix,
"Isn't it worth dying for....?
[ June 02, 2003: Message edited by: boyet silverio ]

Michael Morris
Ranch Hand
Posts: 3451
yep, the method header's a constraint.
Well, duh! :roll: You only need an extra 29 bits to figure it.

boyet silverio
Ranch Hand
Posts: 173
If the resulting computed product is within the expected scope, then fine the computed product can be used with no problems. However if the computed product lies outside the expected scope, the computed product should still be made to be of use (just as if it were within the scope e.g. in calculating) by the enclosing program and not disrupt the continuity of the program's process. I guess that's the intent of the questioner - on how the method can be implemented regardless of which of the previous scenarios arise.
(Regarding why the method header can't be changed is probably due to ... well that could be another area of interest)
[ June 04, 2003: Message edited by: boyet silverio ]

David Hibbs
Ranch Hand
Posts: 374
throw a RuntimeException that has as its message (or as a property) the resulting value. The caller would have to know to handle the exception, of course, but that's what JavaDoc is for!

David Hibbs
Ranch Hand
Posts: 374
The other option of course is to use long values inside the method to do the computation. Then truncate the returned value. The constraints never said that you had to *return* the result!