1,数字转换为字符串获取其每一位
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
char a[10000];
int main()
{
int n;
cin >> n;
string s;
s = to_string(n);
int l = s.size();
for (int i = 0; i < l; i++)
{
a[i] = s[i];
}
for (int i = 0; i < l; i++)
cout << a[i] << " ";
return 0;
}
2,循环整除加取余;
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num;
int i = 0;
cin>>num;
while(num>0)
{
i = num % 10;//计算每一位上的数字
printf("%d\n", i);//打印每一位数字
num = num / 10;//实现位与位之间的遍历
}
return 0;
}
循环条件改为n>0;
#include<bits/stdc++.h>
using namespace std;
int a[10000];
int main()
{
int n;
int s;
int i=0;
cin>>n;
while(n/10)
{
a[i++]=n%10;
n/=10;
}
a[i]=n%10;//取到首位时循环已经跳出;
for(int j=i;j>=0;j--)
cout<<a[j]<<" ";
return 0;
}
3,若位数可知用整除法从前向后取,为正序。
Despite the glorious fa ll colors in the midwest, there is a great deal of time to spend while on a train from St. Louis to Chicago. On a recent trip, we passed some time with the following game.
We start with a positive integer S. So long as it has more than one digit, we compute the product of its digits and repeat. For example, if starting with 95, we compute 9 × 5 = 45. Since 45 has more than one digit, we compute 4 × 5 = 20. Continuing with 20, we compute2 × 0 = 0. Having reached 0, which is a single-digit number, the game is over.
As a second example, if we begin with 396, we get the following computations:
3 × 9 × 6 = 162
1 × 6 × 2 = 12
1 × 2 = 2
and we stop the game having reached 2.
代码:
#include<bits/stdc++.h>
using namespace std;
void ffo(int n)//数为个位前进行循环;
{
int r;
while(n)
{
int t = n;
int s = 1;
while(t)
{
r = t%10;
s*=r;
t/=10;
}
n = s;
if(n/10==0)
{
cout<<" "<<n;
break;
}
cout<<" "<<s;
}
}
int main()
{
int n;
while(cin>>n)
{ if(n==0)break;
cout<<n;
if(n>=10)
{
ffo(n);
}
cout<<endl;
}
return 0;
}