# 解答 - 有幾位數

## [解法一]

### [想法]

• 一邊減少n的位數，一邊增加ans的值

• 可以用 n = n/10 減少n的位數

ans n
0 20160101
1 2016010
2 201601
3 20160
4 2016
5 201
6 20
7 2
8

### [code]

#include<iostream>
using namespace std;

int main()
{
int n;
int ans;

while( cin >> n )
{
ans = 0;
while( n>0 )
{
n = n / 10;
ans = ans+1;
}
cout << ans << endl;
}

return 0;
}


## [解法二]

...

### [code1 - 單純使用if]

#include<iostream>
using namespace std;

int main()
{
int n;

while( cin >> n )
{
if( n>=1 and n<=9 )
{
cout << 1 << endl;
}
if( n>=10 and n<=99 )
{
cout << 2 << endl;
}
if( n>=100 and n<=999 )
{
cout << 3 << endl;
}
if( n>=1000 and n<=9999 )
{
cout << 4 << endl;
}
if( n>=10000 and n<=99999 )
{
cout << 5 << endl;
}
if( n>=100000 and n<=999999 )
{
cout << 6 << endl;
}
}

return 0;
}


### [code2 - 利用while達成]

#include<iostream>
using namespace std;

int main()
{
int n;
int i;

int ans;
int low, up;

while( cin >> n )
{
low = 1;
up = 9;
ans = 1;

while( 1 )
{
if( low<=n and n<=up )
{
cout << ans << endl;
break;
}
low = low*10;
up = up*10+9;
ans = ans+1;
}
}

return 0;
}