leetcode 第9题判断回文数的两种方法对比

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流水线的并行方式执行,加快效率。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值