1020. 数字识别
题目描述
输入一个不多于四位的正整数,求出它是几位数,并分别打印出各位上的数字。
输入
输入一个不多于四位的正整数x。
输出
第一行输出x的位数num,接下来num行从高位到低位输出x的每一位上的数字。
样例输入
123
样例输出
3
1
2
3
数据范围限制
1<=x<=9999
C++代码
#include <iostream>
#include <cassert>
using namespace std;
int main()
{
int x;
cin >> x;
assert(x>=1 && x<=9999);
if (x>=1 && x < 10)
{
cout << "1" << endl;
cout << x << endl;
}
else if(x>= 10 && x<100)
{
cout << "2" << endl;
cout << x/10 << endl;
cout << x%10 << endl;
}
else if (x>=100 && x<1000)
{
cout << "3" << endl;
cout << x/100 << endl;
cout << (x%100)/10 << endl;
cout << (x%100)%10 << endl;
}
else if (x >= 1000 && x<10000)
{
cout << "4" << endl;
cout << x/1000 << endl;
cout << (x%1000)/100 << endl;
cout << ((x%1000)%100)/10 << endl;
cout << ((x%1000)%100)%10 << endl;
}
return 0;
}
另一简洁的求解方法:
#include <iostream>
#include <cassert>
using namespace std;
int main()
{
const int max_digits = 4;
int digitsArray[max_digits];
int numOfDigits = 0;
int x;
cin >> x;
assert(x>=1 && x<=9999);
while(x > 0)
{
digitsArray[numOfDigits++] = x ;
x /= 10;
}
cout << numOfDigits << endl;
for(int i=numOfDigits-1;i>=0; i--)
{
cout << digitsArray[i] << endl;
}
return 0;
}