c - 一个递归函数,判断一个数的数字是否按升序排列

标签 c recursion

我正在练习递归,但我对问题的解决方案似乎不起作用。 我正在尝试编写一个递归代码来确定数字的数字是否按升序排列。这是我的代码:

#include <stdio.h>
int isAscending(int num);
int main(){
    int result;
    result = isAscending(123);//Should print "The number is in ascending order!"
    if (result == 0) {
        printf("The number is in ascending order!\n");
    }
    else {
        printf("The number is not in ascending order!\n");
    }
}
int isAscending(int num) {
    int new = num / 10;
    int result = 0;
    if ((num % 10) == 0) {
        return 0;
    }
    else if ((num % 10) > (new % 10)) {
        result += isAscending(num / 10);
        return result;
    }
    else {
        return 1;
    }
}

最佳答案

这是另一种(简单的)方法。基本思想是,如果我们有一个数字,我们返回肯定,否则我们检查最右边的数字是否大于它左边的数字。我们对剩余的数字执行此操作。

#include <stdio.h>

int isAsc(int i)
{
    int rem = i % 10;    // remainder
    int quo = i / 10;    // quotient

    if (rem == i)
        return 1;
    else if (rem <= (quo % 10))
        return 0;
    else
        return 1 && isAsc(quo);
}

int main(void)
{
    int i = 123123;
    if (isAsc(i))
        printf("%s\n", "Ascending");
    else
        printf("%s\n", "Not ascending");

    return 0;
}

关于c - 一个递归函数,判断一个数的数字是否按升序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46283897/

相关文章:

java - 原始递归偶/奇 - 它到底做了什么?

ruby - 理解递归回溯算法的 Ruby 实现

C语言——从目标文件中调用函数

c - 使用循环数组越界?

c - 在C中使用递归调用时遇到问题

java - 我的数独回溯算法仅在部分时间有效,有人可以帮助我改进它吗?

c - int 指针计算平均值

c - 如何获取通过该指针调用的函数中的指针地址

c - 当从另一个包导出 C 头函数时,将 C 头函数导入到 R 包中的正确方法是什么?

recursion - 计算句子中奇数的个数