forked from nemeritz-ming/ANU_comp6710_Exam_2020_S2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Q1TwoThree.java
45 lines (44 loc) · 1.51 KB
/
Q1TwoThree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package comp1110.exam;
/**
* COMP1110 Final Exam, Question 1.2 (harder)
*
* 5 Marks
*/
public class Q1TwoThree {
/**
* Given a string, return true if the string represents a twothree number,
* or false otherwise.
*
* A twothree number is recursively defined as an integer that is divisible
* by either two or three AND the left n - 1 most digits of the number are
* also a twothree number.
*
* So for example, 6 is a twothree number, and 62 is a twothree number since
* 62 is divisible by 2 and the left n - 1 digits are '6', which is also
* a twothree number. 22222 and 22223 are both twothree numbers. 267 is a
* twothree number but 265 is not since 265 is not divisible by 2 or 3. 2652
* is not a twothree number because 265 is not a twothree number.
*
* An empty string or a string with anything other than a digit from 0-9 is
* not a twothree number.
*
* @param number A number
* @return true if number is a twothree number as defined above.
*/
public static boolean twothree(String number) {
if (number.length() == 0){
return false;
}
if (number.equals("0")){
return false;
}
if (number.length() == 1 && (Integer.parseInt(number) % 2 == 0 || Integer.parseInt(number) % 3 == 0)){
return true;
}
else if (Integer.parseInt(number) % 2 == 0 || Integer.parseInt(number) % 3 == 0){
number = number.substring(0, number.length()-1);
return twothree(number);
}
return false; // FIXME complete this method
}
}