\$\begingroup\$
\$\endgroup\$
0
public static int lastDigit(int a) {
a = a % 10;
if (a <= 0){
a *= -1;
}
return a;
}
This is my solution. The course hasn't taught if else yet, so I'm wondering if there is a way to do it without the if else.
public static int lastDigit(int a) {
a = a % 10;
return a;
}
The problem with this is that it will not print the last digit of a negative number as a positive.
1 Answer 1
\$\begingroup\$
\$\endgroup\$
3
Use Math.abs()
public static int lastDigit(int x) {
return Math.abs(x % 10);
}
TheCoffeeCup
9,5164 gold badges38 silver badges96 bronze badges
-
\$\begingroup\$ Well I feel somewhat stupid. Thanks though \$\endgroup\$user85459– user854592015年10月07日 20:05:47 +00:00Commented Oct 7, 2015 at 20:05
-
\$\begingroup\$ Figured courses should be teaching
if-else
beforestatic
methods invocation... oh wells. \$\endgroup\$h.j.k.– h.j.k.2015年10月08日 00:56:44 +00:00Commented Oct 8, 2015 at 0:56 -
\$\begingroup\$ I make all methods static just to avoid problems. \$\endgroup\$user85459– user854592015年10月08日 17:32:22 +00:00Commented Oct 8, 2015 at 17:32
lang-java