leetcode 第9题判断回文数的两种解法对比
题目
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
解法一(普通解法)
- 代码如下
#include <inttypes.h>
bool isPalindrome(int64_t x){
if (x < 0) return false;
int64_t z = x, y = 0;
while (x) {
y = x % 10 + y * 10;
x /= 10;
}
return z == y;
}
- 执行结果
- 结果分析
可以看到,虽然超过了很多同学,但是时间还是有点长。
解法二(高级解法)
- 代码如下
bool isPalindrome(int64_t x){
if ( __builtin_expect(!!(x < 0), 0)) return false;
int64_t z = x, y = 0;
while (x) {
y = x % 10 + y * 10;
x /= 10;
}
return z == y;
}
- 执行结果
- 结果分析
由于使用了linux的内核函数__builtin_expect(),程序运行效率增加了很多!!!
下面对这个函数进行简单介绍。
这个指令是gcc引入的,作用是允许程序员将最有可能执行的分支告诉编译器。这个指令的写法为:__builtin_expect(EXP, N)。
意思是:EXP==N的概率很大。
一般的使用方法是将__builtin_expect指令封装为likely和unlikely宏。这两个宏的写法如下.
#define likely(x) __builtin_expect(!!(x), 1) //x很可能为真
#define unlikely(x) __builtin_expect(!!(x), 0) //x很可能为假
__builtin_expect((x),1)意思是 x 的值为真的概率更大;
__builtin_expect((x),0)意思是x 的值为假的概率更大。
likely(),执行 if 分支的概率更大,而unlikely(),执行 else 分支的概率更大。cup在执行这条指令的时候减少对分支条件的判断从而可以利用cpu流水线的并行方式执行,加快效率。