天神的密码(可用循环||递归)

这个题的思路很简单,但是细节容易出错,可用循环或递归实现(用空间换时间)!(提交数据显示:递归比循环快3ms)

点击此处查看题目

完整代码:

法1(用循环实现):

#include <iostream>
#include <cstdio>
using namespace std;
int t,n,k;
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&k);
        long long x,y=0,f=1;
        for(int i=0;i<k;i++)
        {
            f*=n;
        }
        x=f;
        while(x>9)
        {
            y=0;//每次计算新的数的时候y一定要初始化!
            while(x)
            {
                y+=x%10;
                x/=10;
            }
            x=y;
        }
        printf("%lld\n",x);
    }
    return 0;
}
 

法2(用递归实现):

#include <iostream>
#include <cstdio>
using namespace std;
int t,n,k;
long long password(long long x,long long y)
{
    y+=x%10;
    x/=10;
    if(x==0)
    {
        x=y;
        if(x<=9)
        {
            return x;
        }
        else{
            return password(x,0);
        }
    }
    else{
        return password(x,y);
    }
}
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&k);
        long long x,f=1;
        for(int i=0;i<k;i++)
        {
            f*=n;
        }
        x=f;
        long long ans=password(x,0);
        printf("%lld\n",ans);
    }
    return 0;
}
 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值