leetcode9(回文数)

    技术2022-07-11  132

    题目:判断一个整数是否是回文数,若是返回true,若不是返回false 题解(1):先判断整数是几位数,然后将整数反转,判断反转后的整数是否与原整数相等

    class solution { private: public: string number(int obj) { long int res = 0; int rest=obj; int count = 0; if (obj < 0)return "False"; if (obj == 0)return"True"; do { rest = rest / 10; count++; } while (rest != 0); for (int i = 0;i < count;i++) { res = res * 10 + (int)(obj / pow(10, i) )% 10; } if (res == obj) { return "True"; } else return "False"; } };

    题解(2):在题解(1)的基础上进行算法优化;只需进行一半反转,判断后一半是否等于前一半即可(如果原数为奇数则在比较时去掉中心数)

    class solution { private: public: string number(int obj) { int res = 0; if (obj < 0)return "False"; if (obj == 0)return"True"; while(obj>res) { res = res * 10 + obj % 10; obj = obj / 10; } if (res == obj||res/10==obj) { return "True"; } else return "False"; } };
    Processed: 0.009, SQL: 9