簡體   English   中英

C - 將 9 轉為 0

[英]C - turn 9 to 0

這是我在這里的第一個問題,我是初學者,代碼是用 C (ANSI C) 編寫的。

代碼應該為遞歸函數中的每個數字返回數字為 (n+1)。(123 -> 234; 801->912; 239->340)

問題是當數字 9 出現並且代碼將其加 1 時,結果是 10 並且它需要變為 0。有沒有辦法處理它而無需專門檢查數字 9?

謝謝!

int swap(int num)
{
    int a,b;
    if (num/10==0)
        return num+1;
    else
    {
        a = num % 10;
        a++;
        b = swap(num / 10);
        return (b * 10) + a;
    }
}

為了在不檢查的情況下獲得下一個數字,您只需使用 MOD 運算符 % 環繞。 所以a = (num % 10 + 1) % 10或者更簡單的a = (num + 1) % 10正如邁克爾所指出的

看來你的意思是以下

#include <stdio.h>

unsigned int increase_digits( unsigned int n )
{
    const unsigned int Base = 10;

    return ( n + 1 ) % Base + ( n / Base == 0  ? 0 : Base * increase_digits( n / Base ) ); 
}

int main(void) 
{
    unsigned int n = 0;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 9;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 13;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 801;

    printf( "%u: %u\n", n, increase_digits( n ) );

    n = 239;

    printf( "%u: %u\n", n, increase_digits( n ) );

    return 0;
}

程序輸出是

0: 1
9: 0
13: 24
801: 912
239: 340

遞歸地,最簡單的方法是:

unsigned swap (unsigned n) {
    if (n < 10) return ++n % 10;
    return 10 * swap(n/10) + swap(n%10);
}

這個函數說的是:

  • 如果n小於 10,則結果比其當前值大 1,取模 10。
    因此,9 將變為 (10 mod 10),即 0。
  • 否則,對最后一位數字和其余數字遞歸應用該算法。
    這里的技巧是,其余的數字是通過將原始數字除以 10,並將接收到的結果乘以 10 得到的。

輸入99打印00的版本

int swap(int num) {
     return num/10 ?
        swap(num/10)*10 + ((num % 10 + 1)%10) :
        (num % 10 + 1) % 10;
}

交換調用函數確定整數參數的長度,然后顯示任何必要的前導零。

void caller(int num) {
     char s[20];             // Assume an int as at most 19 chars...
     sprintf (s, "%d", num); // Could also use log or a loop...

     printf("result: %0*d\n", (int)strlen(s), swap(num));    
}

將其用作

caller(mynumber);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM