LeetCode刷题记录3-求数字是否为回文
来源:互联网 发布:php获取ip地区 编辑:程序博客网 时间:2024/05/29 19:26
求一个数字是否为回文
[2017-11-23修改:增加字符串回文判断]
先写一个本人的笨办法,不过可以判断负数,该方法把整个数字每一位都存了下来(其实可以只存一半):
bool isPalindrome(int x){ int temp = x; vector<int> vec; while (temp) { vec.push_back(temp % 10); temp /= 10; } std::reverse(vec.begin(), vec.end()); //从后往前比较 //只需要比较一半即可 for(int i = 0; i < vec.size() / 2 + 1; ++i) { if (x % 10 != vec[i]) { return false; } x /= 10; } return true;}
接下来是LeetCode的解法:
bool IsPalindrome(int x) { // As discussed above, when x < 0, x is not a palindrome. // Also if the last digit of the number is 0, in order to be a palindrome, // the first digit of the number also needs to be 0. // Only 0 satisfy this property. if(x < 0 || (x % 10 == 0 && if(x < 0 || (x % 10 == 0 && x != 0)) { return false; } int revertedNumber = 0; while(x > revertedNumber) { revertedNumber = revertedNumber * 10 + x % 10; x /= 10; } // When the length is an odd number, we can get rid of the middle digit by revertedNumber/10 // For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123, // since the middle digit doesn''t matter in palidrome(it will always equal to itself), we can simply get rid of it. return x == revertedNumber || x == revertedNumber/10; }
判断回文字符串
提供一个判断回文字符串的方法:
bool isPalindrome__(const std::string& in){ std::string res = std::string(in.begin(), std::mismatch(in.begin(), in.end(), in.rbegin()).first); return in == res;}
mismatch的实际算法源码如下,返回一个pair包括2个容器迭代器的位置:
template<class InputIt1, class InputIt2>std::pair<InputIt1, InputIt2> mismatch(InputIt1 first1, InputIt1 last1, InputIt2 first2){ while (first1 != last1 && *first1 == *first2) { ++first1, ++first2; } return std::make_pair(first1, first2);}
阅读全文
0 0
- LeetCode刷题记录3-求数字是否为回文
- leetcode刷题记录
- leetcode刷题记录
- leetcode刷题记录
- leetcode 刷题记录
- leetcode刷题记录
- Leetcode刷题记录
- Leetcode刷题记录
- leetcode 刷题记录
- LeetCode刷题记录
- 【LeetCode刷题记录】
- LeetCode刷题记录3-Majority Element
- Leetcode刷题记——9. Palindrome Number(回文数字)
- LeetCode刷题记录7-从数组中找出指定条件的3个数字
- leetCode 刷题记录 Candy
- LeetCode 刷题记录 目录
- leetcode 做题记录3
- Leetcode刷题记录 · No.5 Longest Palindromic Substring(最长回文子串)
- Bailian4039 IP地址转换【进制】
- Ubuntu Linux 服务器和桌面的安装!
- LeetCode刷题(38)--Simplify Path
- 基于 OpenWrt 实现 tcpdump 抓包并在 Windows 系统上的 Wireshark 中格式化显示
- JDBC:利用反射封装增删改查操作
- LeetCode刷题记录3-求数字是否为回文
- ZooKeeper
- 使用IDEA搭建SSM框架
- NDK的使用
- 一个Spring Scheduler (Quartz) 动态添加,删除,修改任务的例子
- jupyter中sklearn、opencv无法导入,python中导入正常
- 由深拷贝与浅拷贝引发的引用计数、写时拷贝技术
- hue 大数据的web工具
- NOD1024 (大数据的处理)