其他分享
首页 > 其他分享> > 查看一个数字是不是回环数(对称)

查看一个数字是不是回环数(对称)

作者:互联网

0 回环       1 回环      11 回环      12 不回环     121 回环    1221 回环     12321 回环    123421  不回环     123311 不回环

 

#include<iostream>
#include<cmath>

using namespace std;

int getNumberPow(int a)  //获取一个数字的位数
{
    if (a == 0)
    {
        return 1;
    }

    int ministNum = 1;
    int numPow = 0;
    while(ministNum <= a) //对于 100或者123来说   1<100[123]  10<100[123] 100<=100[123]  1000>100[123]
    {
        ministNum *= 10;
        ++numPow;
    }
    return numPow;
}

void testGetNumberPow()
{
    { int a = 0; cout<< a << "  " << getNumberPow(a) << endl; }
    { int a = 4; cout<< a << "  " << getNumberPow(a) << endl; }
    { int a = 10; cout<< a << "  " << getNumberPow(a) << endl; }
    { int a = 12; cout<< a << "  " << getNumberPow(a) << endl; }
    { int a = 99; cout<< a << "  " << getNumberPow(a) << endl; }
    { int a = 100; cout<< a << "  " << getNumberPow(a) << endl; }
}

bool isLoopbackNum(int a) //判断一个数字是否是回环数
{
    int curpow = getNumberPow(a); //12位数为2   0位数是1  101位数是3
    int halfPow = curpow/2; //一半的位数:偶数的位数的数字正好左右一半, 奇数的位数的数组正好是中间位置
    if(curpow == 1) // 0-9是回环的
    {
        return true;
    }

    int first = a;
    int second = a;

    while(curpow > halfPow) //左边一半和右边一半都一样的话,就没有必要继续比较下去了
    {
        //左边的最高数如果和右边的最低数相等。那么左边扔掉已经比过的最高数,右边扔掉已经比过的最低数. 然后继续比较
        int head = first/(pow(10, (curpow-1)));
        int tail = second%10;

        if (head == tail)
        {
            first %= (int)pow(10, (curpow-1));
            second /= 10;

            --curpow; //既然左边已经扔掉了一个最高数,那么这个左边数字的位数也要-1
        }
        else
        {
            break;
        }
    }

    return (curpow <= halfPow);
}

void testIsLoopbackNum()
{
    { int a = 0; cout<< a << "  " << isLoopbackNum(a) << endl; }
    { int a = 1; cout<< a << "  " << isLoopbackNum(a) << endl; }

    { int a = 11; cout<< a << "  " << isLoopbackNum(a) << endl; }
    { int a = 12; cout<< a << "  " << isLoopbackNum(a) << endl; }

    { int a = 121; cout<< a << "  " << isLoopbackNum(a) << endl; }
    { int a = 1221; cout<< a << "  " << isLoopbackNum(a) << endl; }
    { int a = 12321; cout<< a << "  " << isLoopbackNum(a) << endl; }

    { int a = 123421; cout<< a << "  " << isLoopbackNum(a) << endl; }
    { int a = 123311; cout<< a << "  " << isLoopbackNum(a) << endl; }
}

int main()
{
    //testGetNumberPow();
    //cout<<"------------------"<<endl;
    testIsLoopbackNum();
}

 

标签:10,查看,int,左边,curpow,ministNum,回环,对称
来源: https://www.cnblogs.com/silentNight/p/13976487.html