C++與演算法

解答 - 有幾位數

[解法一]

[想法]

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

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


例如 n=20160101

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;
}



[解法二]

[想法]

如果 1 <= n <= 9 則為 1 位數

如果 10 <= n <= 99 則為 2 位數

如果 100 <= n <= 999 則為 3 位數

如果 1000 <= n <= 9999 則為 4 位數

...

[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達成]

用 low 儲存 1, 10, 100, 1000

用 up 儲存 9, 99, 999, 9999

當 low <= n <= up ,則輸出對應的答案

#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;
}