Issue
A picture of code and test cases:
This is the 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
My code fails nearTen(1) for some reason. please open the picture for details.
public boolean nearTen(int num) {
if (num < 8)
return false;
if (num % 10 == 0)
return true;
while (num / 10 != 0) {
num = num - 10;
}
if (num == 8 || num == 9 || num == 1 || num == 2)
return true;
return false;
}
Solution
public boolean nearTen(int num) {
if(num < 8) {
return false;
} else if(num % 10 == 0) {
return true;
}
while(num / 10 != 0) {
num = num - 10;
}
if(num == 8 || num == 9 || num == 1 || num == 2) {
return true;
}
return false;
}
this is your code, but in first if condition you are doing
if(num < 8)
return false
//so 100% you will fail case => input is 1
And your logic has some issues. Instead of using "/", we can use "%". Reason is you only consider number multiplied by 10.
for example:
- 1 / 11 / 21 / 111 / 555551 / 1000001 => last digit is 1
- 2 / 12 / 122 / 12342 / 5124512 / 1000002 => last digit is 2
for all those numbers we can ignore previous digits, and only consider last digit. Because previous digits are numbers used to multiply 10.
so this answer can be simplified to following code
public boolean nearTen(int num) {
if(num < 0) {
return false;
}
num %= 10;
return num == 8 || num == 9 || (num >= 0 && num <= 2);
}
Answered By - ALargeTom
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.