豎式問題


題目來自於劉汝佳編著的《算法競賽入門經典(第二版)》

問題描述:
找出形如 abc*de (三位數乘以兩位數) 的算式,使得在完整的豎式中,所有數字屬於一個特定的數字集合。輸入數字集合 (相鄰數字之間沒有空格),輸出所有豎式。每個豎式前應有編號,之后應有一個空行。最后輸出解的總數。

樣例輸入:

2357

樣例輸出:

The number of solutions = 1

博主我才疏學淺。。。思來想去還是覺得答案的方法更簡便,於是就不貼出我之前的代碼了,附上答案的代碼,如果有大神想出了其他方法,歡迎在回復中貼出你們的代碼,感謝!o(* ̄▽ ̄*)ブ

答案代碼(已修改,與原書不一致):

#include<stdio.h>
#include<string.h>
int main() {
    char s[20], buf[99];
    int count = 0;
    scanf("%s", s);
    for (int abc = 100; abc <= 999; abc++) 
    {
        for (int de = 10; de <= 99; de++)
        {
            int x = abc*(de % 10);
            int y = abc*(de / 10);
            int z = abc * de;
            sprintf(buf, "%d%d%d%d%d", abc, de, x, y, z);
            int ok = 1;
            for (int i = 0; i < strlen(buf); i++)
                if (strchr(s, buf[i]) == NULL) ok = 0;
            if (ok) {
                printf("<%d>\n", ++count);
                printf("%5d\nX%4d\n-----\n%5d\n%4d\n-----\n%5d\n\n", abc, de, x, y, z);
            }
        }                
    }
    printf("The numbver of solutions = %d\n", count);
    return 0;
}

關於評論中 循環從 111 開始的疑問,博主也同樣持懷疑態度,因此將代碼答案更新為從 100 開始,關於這個疑問可以參考這個網址

http://tieba.baidu.com/p/3177382627?red_tag=h1918510311


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM