栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Python

Leetcode 9 回文数 java String和StringBuilder

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leetcode 9 回文数 java String和StringBuilder

题目:

给你一个整数 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) ----- 构造转换

 

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1038378.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号