zoukankan      html  css  js  c++  java
  • 算法竞赛入门经典ch3_ex4竖式问题

    找出所有形如abc*de(三位数乘以两位数)的算式,使得在完整的竖式中,
    所有数字都属于一个特定的数字集合。 输入数字集合(相邻数字之间没有空格),输出所有
    竖式。 每个竖式前应有编号,之后应有一个空行。 最后输出解的总数。

    样例输入:

    2357

    样例输出:

    2357
    <1>
      775
    X  33
    -----
     2325
    2325
    -----
    25575
    
    The number of solutions = 1

    疑问

    • 为什么从111开始?为什么不是100和10

    code

    //竖式问题
    #include <stdio.h>
    #include <string.h>
    int main()
    {
        char s[20], buf[99];
        int count = 0;
        scanf("%s", s);
        for (int abc = 111; abc <= 999; abc++)
        {
            for (int de = 11; de <= 99; de++)
            {
                //计算2个中间数字和结果
                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; //flag,判断是否符合条件
                for (int i = 0; i < strlen(buf); i++)
                {
                    if (strchr(s, buf[i]) == NULL)
                    {
                        ok = 0;
                        //break;//减少计算次数
                    }
                }
                if (ok)//legal
                {
                    //print
                    printf("<%d>
    ", ++count);
                    printf("%5d
    X%4d
    -----
    %5d
    %4d
    -----
    %5d
    
    ", abc, de, x, y, z);
    
                }
            }
        }
        // print result
        printf("The number of solutions = %d
    ", count);
    
        return 0;
    }

    总结

    • sprintf

      printf输出到屏幕,fprintf输出到文件,而sprintf输出到字符串。

      char buf[99];
      sprintf(buf, "%d%d%d%d%d", abc, de, x, y, z);
    • strchr
    char s[20];
    if (strchr(s, buf[i]) == NULL)
        {
            ok = 0;
        }
    • strlen

      strlen(s)返回的就是结束标记之前的字符个数。 因此这个字符串中的各个字符依次是s[0], s[1],…, s[strlen(s)-1],而s[strlen(s)]正是结束标记“”。

    • C语言的字符串是以空字符“”结尾的。
    • 由于字符串的本质是数组,它也不是“一等公民”,只能用strcpy(a, b),strcmp(a, b), strcat(a, b)来执行“赋值”、 “比较”和“连接”操作,而不能用“=”、 “==”、
      “<=”、 “+”等运算符。 上述函数都在string.h中声明。
  • 相关阅读:
    UML模型的基本概念
    Asp.net 2.0 发送电子邮件
    生活多了些颜色
    FLASH调用网页上的JS方法,以及FLASH全屏播放的方法
    HTC编程思想
    实用的SQL精妙语句
    自己写的封装好的简单的AJAXjavascript
    SQL Server对象名
    windows开关机日志
    RegisterWindowMessage
  • 原文地址:https://www.cnblogs.com/shanchuan/p/8150302.html
Copyright © 2011-2022 走看看