sting反向迭代器的使用

1243阅读 0评论2009-12-04 jiangwen127
分类:


#include <iostream>
#include <string>
using namespace std;

void printout(int count)
{
        if (0 == count)
        {
            cout << "No carry operation." << endl;
        }
        else if (1 == count)
        {
            cout << "1 carry operation." << endl;
        }
        else
        {
            cout << count << " carry operations." << endl;
        }
}

int main(int argc, char *argv[])
{
    int carray, sum, count;
    string s1, s2;
    while ((cin >> s1, cin >> s2) && (0 != s1.compare("0") || 0 != s2.compare("0")))
    {
        string::reverse_iterator ite1, ite2, end1, end2;
        ite1 = s1.rbegin();
        ite2 = s2.rbegin();
        end1 = s1.rend();
        end2 = s2.rend();
        carray = sum = count = 0;
        while (ite1 != end1 && ite2 != end2)
        {
            sum = (*ite1 - '0') + (*ite2 - '0');
            if (1 == carray)
            {
                sum += 1;
            }
            if (sum > 9)
            {
                carray = 1;
                count++;
            }
            else
            {
                carray = 0;
            }
            ite1++;
            ite2++;
        }
        if (ite1 == end1 && ite2 == end2)
        {
            printout(count);
            continue;
        }
        if (ite1 == end1)
        {
            while (ite2 != end2)
            {
                if (carray == 1 && *ite2 == '9')
                {
                    count++;
                }
                else
                {
                    break;
                }
                ite2++;
            }
        }
        else if (ite2 == end2)
        {
            while (ite1 != end1)
            {
                if (carray == 1 && *ite1 == '9')
                {
                    count++;
                }
                else
                {
                    break;
                }
                ite1++;
            }
        }
        printout(count);
    }
}


上一篇:一个产生随机数的脚本
下一篇:dp备忘录 pku2704