LeetCode-- Palindrome Number
2015-12-02 10:29
274 查看
题目描述:
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
本题就是判断一个整数是否为回文。
特殊要求是不能转化为string,其实这个限制我认为不是很有意义,因为现实应用中很少会有要求。
思路:
1. 一次遍历,不断/10,得到x的位数 : digits
2. 遍历digits[0, len/2], 使用n1,n2分别表示x从右边“拿掉”1位和x从左“拿掉”一位之后的数,拿掉的数分别为x1,x2
x1 = n1%10;
n1/=10;
x2 = n2 / Math.Pow(len(digits - i))
n2 -= x2 * Math.Pow(len(digits - i)),其中i∈[0, len/2]
实现代码:
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
本题就是判断一个整数是否为回文。
特殊要求是不能转化为string,其实这个限制我认为不是很有意义,因为现实应用中很少会有要求。
思路:
1. 一次遍历,不断/10,得到x的位数 : digits
2. 遍历digits[0, len/2], 使用n1,n2分别表示x从右边“拿掉”1位和x从左“拿掉”一位之后的数,拿掉的数分别为x1,x2
x1 = n1%10;
n1/=10;
x2 = n2 / Math.Pow(len(digits - i))
n2 -= x2 * Math.Pow(len(digits - i)),其中i∈[0, len/2]
实现代码:
public class Solution { public bool IsPalindrome(int x) { if(x < 0){ return false; } if(x == 1){ return true; } // first loop , to know how many digit var digits = 0; var n = x; while(n != 0){ n/=10; digits++; } int n1 = x; // digits from left to right int n2 = x; // digits from right to left for(var i = 1;i <= digits/2; i++){ var p = Math.Pow(10, digits-i); int x1 = n1 % 10; int x2 = (int) (n2 / p); if(x1 != x2){ return false; } n1 /= 10; n2 -= (int)(x2 * p); } return true; } }
相关文章推荐
- SQL----函数
- watchOS 2 教程(四): Watch Connectivity
- c/c++ 数字转字符串, 字符串转数字
- SpringMVC整合Tiles框架
- android EditText禁止复制粘贴完整代码
- D. Mike and Feet---cf548D(最值)
- jquery图片预览
- 旧文重整之-> HASH集
- 局部保留投影(LPP)推导
- mysql 安装脚本
- LeetCode-- Move Zeroes
- OpenCV图像金字塔:高斯金字塔、拉普拉斯金字塔与图片尺寸缩放
- HTML标签自定义属性
- 安卓5.0后httpclient
- Apache配置缺失msvcr100.dll msvcr110.dll
- JS弹出框,弹出层
- HBase默认参数说明
- JS操作DOM元素属性和方法
- leetcode Palindrome Linked List--简单重点
- Hexagon SDK之Audio APPI详解