问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3840 访问。

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

输入: 121

输出: true

输入: -121

输出: false

解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

输入: 10

输出: false

解释: 从右向左读, 为 01 。因此它不是一个回文数。

进阶:

你能不将整数转为字符串来解决这个问题吗?


Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Input: 121

Output: true

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.

Input: 10

Output: false

Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3840 访问。

public class Program {

    public static void Main(string[] args) {
var x = 121;
var res = IsPalindrome(x);
Console.WriteLine(res); x = -567;
res = IsPalindrome2(x);
Console.WriteLine(res); x = 168861;
res = IsPalindrome3(x);
Console.WriteLine(res); Console.ReadKey();
} private static bool IsPalindrome(int x) {
//计算反转值
if(x < 0) return false;
var res = 0L;
var value = x;
while(x != 0) {
res = res * 10 + x % 10;
x = x / 10;
}
return res == value;
} private static bool IsPalindrome2(int x) {
//反转字符串
if(x < 0) return false;
var arr = x.ToString().ToCharArray();
Array.Reverse(arr);
return x.ToString() == new string(arr);
} private static bool IsPalindrome3(int x) {
//栈
if(x < 0) return false;
var palindrome = x.ToString();
var stack = new Stack<char>();
for(var i = 0; i < palindrome.Length / 2; i++) {
stack.Push(palindrome[i]);
}
//奇数时,往后移一位
int pos = 0;
if(palindrome.Length % 2 == 1) {
pos = 1;
}
for(var i = palindrome.Length / 2 + pos; i < palindrome.Length; i++) {
if(palindrome[i] != stack.Pop()) return false;
}
return true;
} }

以上给出3种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3840 访问。

True
False
True

分析:

显而易见,以上3种算法的时间复杂度均为: 

最新文章

  1. pip 安装 MySQL-python 失败
  2. spring mvc处理静态资源
  3. Python文件处理之文件写入方式与写缓存(三)
  4. Debian 7 安装 Emacs 24.3
  5. L002-oldboy-mysql-dba-lesson02
  6. linux 挂载 镜像文件
  7. VC实现图片拖拽及动画
  8. POJ-1995 Raising Modulo Numbers---快速幂模板
  9. SQL Server 连接 MySQL
  10. leetcode 921. 使括号有效的最少添加(Python)
  11. SQL Server并发操作单个表时发生在page页面级的死锁
  12. C#设计模式(2)——工厂模式
  13. learning makefile grammar
  14. 5分钟快速打造WebRTC视频聊天&lt;转&gt;
  15. lucene中文分词——(四)
  16. 测序中Q20 Q30 Q40
  17. C#中IDisposable的用法
  18. 用Shell编写项目发布脚本
  19. macOS 中文件属性有at符号
  20. kali虚拟机安装后操作[配置ssh,安装vmtools,更新源]

热门文章

  1. [Qt插件]-03创建Qt Designer自定义部件
  2. Ethical Hacking - NETWORK PENETRATION TESTING(21)
  3. Python Ethical Hacking - KEYLOGGER(3)
  4. CPU核数
  5. epic游戏平台如何启用认证器应用程序/二次验证码/谷歌身份验证器?
  6. Linux 终端最全推荐(建议收藏)
  7. Python3的一些基本输入输出
  8. js的传递方式
  9. UUID字符串使用
  10. SpringSecurity+Oauth2+Jwt实现toekn认证和刷新token