反序数--清华考研机试

自己尝试使用的方法:超时了

复制代码
#include <cstdio>
#include <iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
    for(int n=1000;n<=1111;n++)
    {
        int a,b,c,d,e,f,g,h;
        int m=9*n;
        a=n-(n/10)*10;
        n=n/10;
        b=n-(n/10)*10;
        n=n/10;
        c=n-(n/10)*10;
        n=n/10;
        d=n-(n/10)*10;
        
        e=m-(m/10)*10;
        m=m/10;
        f=m-(m/10)*10;
        m=m/10;
        g=m-(m/10)*10;
        m=m/10;
        h=m-(m/10)*10;
        
        if(a==h&&b==g&&c==f&&d==e)
        cout<<n<<endl;
        
    }
    return 0;
} 
复制代码

看答案,自己又想了一个

复制代码
#include <cstdio>
#include <iostream>
#include<string>
#include<cstring>
using namespace std;
int re(int a)
{
    int b=0;
    b+=a/1000;
    a=a-a/1000*1000;
    b+=a/100*10;
    a=a-a/100*100;
    b+=a/10*100;
    a=a-a/10*10;
    b+=a*1000;
    return b;
}
int main()
{
    for(int n=1000;n<=9999;n++)
    {
        if(n*9==re(n))
        cout<<n<<endl;
    }
    return 0;
} 
复制代码

但是也出了一些问题,在re函数中,一开始没给b赋值,导致b一直累加,所以最后没得出结果。

答案使用的方法更简洁,而且有一定的思维量。

复制代码
#include <cstdio>
#include <iostream>
#include<string>
#include<cstring>
using namespace std;
int re(int a)
{
    int b=0;
    while(a!=0)//四次循环
    {
        b*=10;// 0*10 4*10 43*10 432*10 乘四次 
        b+=a%10;
        a=a/10;//1234 123 12 1 0 
     } 
    return b;
}
int main()
{
    for(int n=1000;n<=9999;n++)
    {
        if(n*9==re(n))
        cout<<n<<endl;
    }
    return 0;
} 
复制代码

 

posted @   Tomorrow1126  阅读(174)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示