我把这个作业作为家庭作业,但我不知道该怎么做:
Input is a string of the numbers 1, 2 and 3.
You need to build a function that determines if the number represented by the string is divisible by 3.Rules:
- No loops.
- No math operations (+,-,*,/,%) on the number.
- Use recursion.
Hint: if the sum of the digits of a number is divisible by 3 - so is the number.
我尝试使用提示想出一个算法来执行此操作,但它不起作用(如果 1 和 2 出现相同的次数,则该数字可以被 3 整除。但是如果该数字由只有 1 或 2 时它仍然可以被整除,我们发现自己又遇到了同样的问题)。
有什么想法吗?
最佳答案
好吧,你能傻到什么程度?入口点是divBy3_0
,只需用字符串调用即可。
bool divBy3_0(char const *n);
bool divBy3_1(char const *n);
bool divBy3_2(char const *n);
bool divBy3_0(char const *n) {
switch(*n) {
case '1': return divBy3_1(&n[1]);
case '2': return divBy3_2(&n[1]);
case '3': return divBy3_0(&n[1]);
}
return true;
}
bool divBy3_1(char const *n) {
switch(*n) {
case '1': return divBy3_2(&n[1]);
case '2': return divBy3_0(&n[1]);
case '3': return divBy3_1(&n[1]);
}
return false;
}
bool divBy3_2(char const *n) {
switch(*n) {
case '1': return divBy3_0(&n[1]);
case '2': return divBy3_1(&n[1]);
case '3': return divBy3_2(&n[1]);
}
return false;
}
关于c - 无需使用数学运算符即可确定数字是否能被 3 整除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41766218/