uva725

除法(Division,uva725)

输入整数n,,按从小到大的顺序输出所有形如abcde/fghij=n的表达式,其中a~j恰好为数字0~9的一个排列(可以有前导0),

输入:多组数据,最后以0作为结束标记

输出:每组数据间用空行隔开,如果无解则输出 ``There are no solutions for N."

2<=n<=79。

样例输入:

62

样例输出:

79546/01283=62

94736/01528=62

方法1:枚举,使用如果数字i出现,则f[i]=1,最后统计f数组中1的个数即可。

如何分离出i的每个数字

方法1: f[i%10]=f[i/10%10]=f[i/100%10]=f[i/1000%10]=f[i/10000]=1;

方法2:

    int t=i;

  while (t!=0){  f[t%10]=1;t=t/10;}

#include<iostream>
using namespace std;
int f[10];
int main(){
    int n,p, first=0;//是否为输出的第一个数的标记,用来控制2组测试数据间的空格 
    while (cin>>n&&n!=0){
        if (first)cout<<endl;
        p=0;
        for (int i=0;i<=9;i++) f[i]=0;
        for(int i=1000;i<=55555;i++){
            for (int j=0;j<=9;j++) f[j]=0;
            if (i<10000)
                f[i%10]=f[i/10%10]=f[i/100%10]=f[i/1000%10]=1;
            else 
                f[i%10]=f[i/10%10]=f[i/100%10]=f[i/1000%10]=f[i/10000]=1;
            int j=n*i;
            if (j<100000) 
                f[j%10]=f[j/10%10]=f[j/100%10]=f[j/1000%10]=f[j/10000]=1;
            int s=0;
            for (int k=0;k<=9;k++)    s=s+f[k];
            if (i<10000&& s==9&&f[0]==0) {cout<<j<<" / 0"<<i<<" = "<<n<<endl;p=1; }
            if (s==10) {cout<<j<<" / "<<i<<" = "<<n<<endl;p=1; }
        first=1;
    }
    if(p==0) cout<<"There are no solutions for "<<n<<"."<<endl;
    }
        return 0;    
}

 方法1简化版

不需要判断是4位数还是5位,因为4位数时f[i/10000]=f[0]=1,此时4位数恰好需要有前导0

另外输出时利用printf的特点,也不需要判断是几位数

#include<iostream>
#include<cstdio>
using namespace std;
int f[10];
int main(){
    int n,p, first=0;//是否为输出的第一个数的标记,用来控制2组测试数据间的空格 
    while (cin>>n&&n!=0){
        if (first)cout<<endl;
        p=0;
        for (int i=0;i<=9;i++) f[i]=0;
        for(int i=1000;i<=99999;i++){
            for (int j=0;j<=9;j++) f[j]=0;
            f[i%10]=f[i/10%10]=f[i/100%10]=f[i/1000%10]=f[i/10000]=1;
            int j=n*i;
            if (j<100000) 
                f[j%10]=f[j/10%10]=f[j/100%10]=f[j/1000%10]=f[j/10000]=1;
            int s=0;
            for (int k=0;k<=9;k++)    s=s+f[k];
            if (s==10) {printf("%d / %05d = %d
",j,i,n);p=1;}
            first=1;
    }
    if(p==0) cout<<"There are no solutions for "<<n<<"."<<endl;
    }
        return 0;    
}
View Code

 特别提醒:本题中可能有前缀0

if(s==10||s==9&&p[0]==0) //注意有前缀0的情况

原文地址:https://www.cnblogs.com/ssfzmfy/p/4612719.html