题目:
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如,121 是回文,而 123 不是。
思路1:转字符串
python
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ return str(x) == str(x)[::-1]
java
public class solution9 { public static void main(String[] args) { //主方法 int x = 1234321; solution9 sol = new solution9(); System.out.println(sol.isPalindrome(x));//调用方法 } public boolean isPalindrome(int x) { if(x < 0){ return false; } String strx = "" + x; String newStr = new StringBuilder(""+x).reverse().toString(); return strx.equals(newStr); } }
思路2,翻转数字
python
class Solution(object): def isPalindrome(self, x): if x < 0 : return False new_x = 0 #翻转后的数 old_x = x while x > 0: temp = x % 10 #取最后一位数 new_x = new_x * 10 + temp #尾数变头数 x = x // 10 #去掉最后一位数 return new_x == old_x l9 = Solution() res = l9.isPalindrome(1234321) print(res)
java
public class solution9_2 { public static void main(String[] args) { solution9_2 sol = new solution9_2(); boolean res = sol.isPalindrome(1234321); System.out.println(res); } public boolean isPalindrome(int x){ if(x < 0){ return false; } int new_x = 0; int old_x = x; while(x > 0){ new_x = new_x * 10 + x % 10; x = x /10; } return new_x == old_x; } }
****解题思路非原创,只作为笔记记录
java学习笔记
String
String构造方法:
String str = new String() //创建一个空白字符串对象,无任何内容
String str = new String(char[] chs) // 根据字符数组内容创建字符串
String str = new String(byte[] byt) // 根据字节数组内容创建字符串
String str = "ABC" //直接赋值
String对象的特点:
通过new创建的对象,每次都会new一个内存空间,即使内容相同也不是同一个对象(地址不同)
字符串方法:
== | 基本类型:比较的数据值是否相同 引用类型:比较的地址值是否相同 |
public boolean equals() | 将此字符串与指定对象进行比较内容是否相同,参数直接传递一个字符串对象。 |
public char charAt(int index) | 返回指定索引处的char值 |
public int length() | 返回字符串的长度 |
字符串拼接:String str = "" + 123 -> "123"
StringBuilder
对字符串进行拼接时,每次拼接都会创建一个新的对象,浪费时间和内存,可以利用StringBuilder解决此问题,StringBuilder内容可变。
public StringBuilder() 创建一个空白可变字符串对象,不含有任何内容。
public StringBuilder(String str) 根据字符串内容,创建可变字符串对象。
方法:
public StringBuilder append(任意类型) | 添加数据,并返回对象本身 |
public StringBuilder reverse() | 返回相反的字符数列 |
String和StringBuilder相互转换:
public String toString() ------- 利用方法转换
public StringBuilder (String s) ----- 构造转换