Digital Roots
https://www.nowcoder.com/practice/cef727d0af33479c9fb4a9c120702414?tpId=40&tqId=21403&rp=1&ru=%2Fta%2Fkaoyan&qru=%2Fta%2Fkaoyan%2Fquestion-ranking&tab=answerKey
常规的循环写法:
#include<cstdio>
#include<iostream>
using namespace std;
int main(void)
{
int n;
while(cin>>n)
{
int sum=0;
int temp=n;
while(n>10)
{
temp=n;
sum=0;
while(temp)
{
sum+=temp%10;
temp/=10;
}
n=sum;
}
cout<<n<<endl;
}
return 0;
}
递归写法:
#include<cstdio>
#include<iostream>
using namespace std;
#define ll long long
ll n;
ll dfs(int sum)
{
ll a=0;
while(sum)
{
a=a+sum%10;
sum/=10;
}
if(a>=10) return dfs(a);
else return a;
}
int main(void)
{
while(cin>>n)
{
printf("%d\n",dfs(n));
}
return 0;
}
神奇的口袋
https://www.nowcoder.com/practice/9aaea0b82623466a8b29a9f1a00b5d35?tpId=40&tqId=21390&rp=1&ru=%2Fta%2Fkaoyan&qru=%2Fta%2Fkaoyan%2Fquestion-ranking&tab=answerKey
#include<cstdio>
#include<iostream>
using namespace std;
int a[30];
bool b[30];
int n;
int ans;
void dfs(int index)
{
if(index==n)
{
int sum=0;
for(int i=0;i<n;i++)
{
if(b[i])
sum+=a[i];
}
if(sum==40)
ans++;
return;
}
b[index]=true;//选
dfs(index+1);
b[index]=false;//不选
dfs(index+1);
}
int main(void)
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
dfs(0);
cout<<ans<<endl;
return 0;
}
Fibonacci
https://www.nowcoder.com/practice/17ad6908e36a49f4b06ea96936e8bb25?tpId=40&tqId=21427&rp=1&ru=%2Fta%2Fkaoyan&qru=%2Fta%2Fkaoyan%2Fquestion-ranking&tab=answerKey
#include<cstdio>
#include<iostream>
using namespace std;
int a[30];
int n;
int F(int a)
{
if(a==0)
return 0;
if(a==1)
return 1;
return F(a-1)+F(a-2);
}
int main(void)
{
cin>>n;
cout<<F(n)<<endl;
return 0;
}