【C++】判断一个数是不是回文数,不使用额外的空间
来源:互联网 发布:怎样看待网络流行语 编辑:程序博客网 时间:2024/05/17 04:20
题目描述:Determine whether an integer is a palindrome. Do this without extra space.
方法一:将整数转换成字符串,然后用前后两个指针,来判断是不是回文。代码如下:
bool isPalindrome(int x) { if(x<0) return false; int length=0,temp=x; while(temp){ length++; temp/=10; } //一个特殊的情况是x==0 if(x==0) length++; char str[length]; //考虑到题目要求不能使用额外的空间,不知这样使用sprintf函数会不会占用多余的空间 sprintf(str,"%d",x); cout<<"s:"<<str<<" "<<length<<endl; int i=0,j=length-1; while(i<=j){ if(str[i]!=str[j]) return false; if(str[i]==str[j] && i<=j){ i++; j--; } } if(i>=j) return true;}
由于方法一中使用了sprintf来将整数转换成字符串,不知这个函数是否会使用额外的空间。方法二是完全使用除法运算,空间复杂度为O(1):
bool isPalindrome2(int x) { if(x<0) return false; int length=0,temp=x; while(temp){ length++; temp/=10; } if(length==1) return true; int half_len = length/2; int frontNum=0,rearNum=0,divisor=1; temp=x; for(int i=0;i<half_len;i++){ divisor*=10; rearNum=rearNum*10+temp%10; temp=temp/10; } if(length%2==1) divisor*=10; frontNum=x/divisor; if(frontNum==rearNum) return true; else return false;}
阅读全文
0 0
- 【C++】判断一个数是不是回文数,不使用额外的空间
- python实现不使用额外的空间判断输入数字是否是回文数
- 【算法】不利用额外空间判断回文数
- 不用额外空间判断一个数是否是回文形式
- 【c语言】判断一个数是不是回文数
- 【C语言】判断一个数是不是回文数
- 判断一个数是不是回文数
- 判断一个数是不是回文数
- 判断一个数是不是回文数
- 判断一个数是不是回文数
- 判断一个数是不是回文数
- 判断一个数是不是回文数
- 判断一个数是不是回文数
- 递归判断一个数是不是回文数
- LintCode判断一个数是不是回文数
- 判断一个数的n进制是不是回文数
- 判断是不是回文数
- 判断是不是回文数
- Eureka的一些概念
- 怎么用VC打开qt的工程
- Android ListView去掉分界线的三种方式
- Linux文件和扩展名
- 10.28模拟
- 【C++】判断一个数是不是回文数,不使用额外的空间
- logback高级特性使用(三)
- ubuntu16.04 使用sublime 运行C程序
- Anaconda环境基本配置
- 浅谈函数的调用,栈帧的创建和销毁
- QT4.6.3 + VS2008安装配置全过程
- 数据结构排序--归并排序
- SDUT-2780 Pots(BFS)
- pthread_create 内存泄漏