首页 > 其他分享 >leetcode倒转整数--snprintf性能不行

leetcode倒转整数--snprintf性能不行

时间:2022-12-01 17:04:15浏览次数:46  
标签:std return snprintf -- sum int INT buf leetcode


#include <stdio.h>
#include <string.h>
#include <iostream>
#include <limits>
int reverse(int x) {
long sum = 0;
while (x) {
sum = sum * 10 + x % 10;
x = x / 10;
}
if (sum > std::numeric_limits<int>::max() || sum < std::numeric_limits<int>::min()) {
return 0;
}
return static_cast<int>(sum);
}
int reverse1(int x) {
static const char *MAX_INT_VALUE = "2147483647";
static const int MAX_INT_SIZE = 10;
bool positive = true;
char buf[32] = "";
if (x < 0) {
if (std::numeric_limits<int>::min() == x) {
return 0;
}
x = -x;
positive = false;
}
//std::string str = std::to_string(x); // 比snprintf更慢
snprintf(buf, sizeof(buf), "%d", x); // 慢
return 0;
char ch = 0;
int len = strlen(buf);
int i = 0;
int j = len -1;
if ((MAX_INT_SIZE == len) && buf[j] >= '3') {
return 0;
}
for (;i < j;i++,j--) {
ch = buf[i];
buf[i] = buf[j];
buf[j] = ch;
}
if (MAX_INT_SIZE == len) {
if (strcmp(buf, MAX_INT_VALUE) > 0) {
return 0;
}
}
if (true == positive) {
return atoi(buf);
}
return -atoi(buf);
}
int main() {
for (int i = -99999999;i <= 9999999;i++) {
reverse(i); // 3.317s
// reverse1(i); // 10.649s
}

return 0;
}

leetcode倒转整数--snprintf性能不行_ios

标签:std,return,snprintf,--,sum,int,INT,buf,leetcode
From: https://blog.51cto.com/u_15899033/5902967

相关文章

  • 网站搭建过程
    1Linux建站1.1红帽LAMP建站基础环境[root@localhost/]#cat/etc/redhat-releaseRedHatEnterpriseLinuxServerrelease7.2(Maipo)[root@localhost/]#unam......
  • 使用inotify向文件添加一段注释
    一需求简介:在ubuntu系统上任意打开一个文件(vim,touch获取其它方式),该新建的文件都会被写入一段注释。二实现:编译环境:ubuntu18.04实现方法:利用inotify监控目录这个特性,当在......
  • 代码绑核后调用system占用CPU分析
    一system函数分析1.函数原型:intsystem(constchar*command)参数command一般是一条可被/bin/sh-c执行的字符串,可以是"ls-l"这样的shell命令,也可以是"./Test"这样的二进......
  • springboot启动报错:Failed to start bean ‘documentationPluginsBootstrapper‘
    今天启动时,突然报了这个错误,网上查了下是springboot版本和swagger版本之间的问题,解决办法如下:原因:这是因为Springfox使用的路径匹配是基于AntPathMatcher的,而SpringBoot......
  • copy member from void * array
    void*copy_element(constvoid*src[],intcnt,size_tsize){void*result=0;char*p;size_tnum=0;for(inti=0;i<cnt;i++){num+=size;res......
  • leetcode-搜索插入位置
    intsearchInsert(std::vector<int>&nums,inttarget){inti=0;intsize=nums.size();for(;i<size;i++){if(nums[i]>=target){......
  • insmod提示“Invalid module format”
    1.现象:编译usb驱动程序,提示2.原因:在不同机器上编译了驱动导致无效格式3.解决:在目标机器搭建好编译环境,执行编译内核操作即可makemakeinstallmodprobeusbnetinsmodXXX.kom......
  • Deepin 20.7 /usr/bin/sudo 必须属于用户 ID 0(的用户)并且设置 setuid 位
    Deepin20.7sudo异常现象  分析原因sudo的配置、权限等原因造成,经检查后发现/bin下的权限改为了user,修改owner和group为root恢复  解决方法chmod4755/u......
  • boyer_moore与find对比测试
    #include<iostream>#include<string>intboyer_moore(conststd::string&src,conststd::string&des){intsize=src.size();intlen=des.size();if(......
  • 独占任务模型
    一需求:多个请求者可向系统发送指令,但系统只有一个任务执行执行指令。当任务执行指令时,又收到新的指令,那任务将不会继续执行以前指令,而是执行新指令。二实现:系统有一个独立......