c - 无需使用数学运算符即可确定数字是否能被 3 整除

标签 c recursion

我把这个作业作为家庭作业,但我不知道该怎么做:

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;
}

See it live on Coliru

关于c - 无需使用数学运算符即可确定数字是否能被 3 整除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41766218/

相关文章:

c - 从 fgets() 输入中删除尾随换行符

c - 按位取余运算符

编译 sqlite 合并以获取用户身份验证会引发错误 C2129 和 C1083

javascript - 柯里化(Currying)形式的递归函数可以是尾递归吗?

c - 我什么时候应该释放双指针?

c - 是否可以从 C 中的文件开头删除 N 个字节?

python - 如何递归打印变量的内容,包括数据和对象属性?

python - 汉诺塔调用追踪

language-agnostic - 递归处理器或编程语言/编译器或两者的功能的能力吗?

Javascript - 您可以使用 .shift() 在递归过程中更改数组吗?