Problem:
Given a non-negative number "num", return true if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2. See also: Introduction to Mod
nearTen(12) → true
nearTen(17) → false
nearTen(19) → true
Solution:
public boolean nearTen(int num) { if (num % 10 < 3 || num % 10 >=8) return true; else return false; }
shorter - return (num+2)%10<5;
ReplyDeleteWhat is the significance of 5 in this code?
Delete
ReplyDeleteYour cell phone rings. Return true if you should answer it. Normally you answer, except in the morning you only answer if it is your mom calling. In all cases, if you are asleep, you do not answer.
public boolean nearTen(int num) {
ReplyDeletereturn num % 10 <= 2 || 10 - num % 10 <= 2;
}
public boolean nearTen(int num) {
ReplyDeletereturn (num % 10 <= 2) != (num % 10 >= 8);
}
What is the solution in C?
ReplyDeletereturn num%10<3||num%10>7;
ReplyDeletepublic boolean nearTen(int num) {
ReplyDeletereturn num%10 <= 2 || num%10 >= 8;
}
public boolean nearTen(int num) {
ReplyDeletereturn num%10==0 || num%10==1 || num%10==2 || num%10==8 || num%10==9;
}