Palindrome Number

        判断回文数,题目要求是不要产生的多余的空间。因为我自己的基础不是很牢靠,不太清楚什么叫不产生多余的空间,我正常的生成变量,所有判断尽量在循环中完成最后提交通过了。代码如下

        

public class Solution {
	public  boolean result = true;
	public String first;
	public String end;
	 public boolean isPalindrome(int x) {
	
		   if(x<0)
		   {
			   result = false;
		   }
		   else
		   {
			   String str = String.valueOf(x);      //为了方便提取首位和末尾,将输入的数字转换成了字符串
			   int i = str.length();
			   while(i>2)
			   {
				    first = str.substring(0, 1);
				    end   = str.substring(i-1, i);

				   
				 
				   if(first.equals(end))
				   {
					   
					   str = str.substring(1, i-1);
					   i= str.length();
					   
				   }
				   else
				   {
					   result = false;
					   break;
				   }
			   }
			   if(i==2)
			   {
				   
				   if(!str.subSequence(0,1).equals(str.subSequence(1,2)))
					   result = false;
			   }
		   }
		   return result;
	    }
	
	    
}

       


       提交通过。之后觉得自己的方法有点冗余,上网上搜索其他人的方法。看到了一个比较简短的代码,我为了方便提取整数的首末两位,将数字转换为了字符,而下面的代码不用转换,但是首先要计算整数的位数。

       

public class Solution {
    public boolean isPalindrome(int x) {
        //negative numbers are not palindrome
		if (x < 0)
			return false;
 
		// initialize how many zeros
		int div = 1;
		while (x / div >= 10) {       //计算输入数字的位数
			div *= 10;
		}
 
		while (x != 0) {
			int left = x / div;         
			int right = x % 10;
 
			if (left != right)
				return false;
 
			x = (x % div) / 10;      //删除首位和末尾
			div /= 100;
		}
 
		return true;
    }
}

     这个代码的思路比较好。比较讨巧,但是多了循环次数,在提交运行的时候运行时间比我自己写的长了将近一倍。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值