LeetCode(Hot100)——7:数字反转

复习

(1)char charAt(int index)

返回指定索引处的 char 值。

(2)String substring(int beginIndex, int endIndex)

返回一个新字符串,它是此字符串的一个子字符串。

(3)String substring(int beginIndex)

返回一个新的字符串,它是此字符串的一个子字符串。

(4)Integer.parseInt() 是 Java 中的一个方法,用于将字符串转换为整数类型的数据。它的作用是将一个字符串参数解析为带符号的十进制整数

代码

java 复制代码
public class LeetCode7 {
    @Test
    public void test(){
        //int x=-123;
        int x=1222230;
        System.out.println(reverse(x));
    }

    public int reverse(int x){

        String xstr=x+"";
        //1.判断是否为负数
        String fs="";
        if(xstr.substring(0,1).equals("-")){
            fs="-";
            xstr=xstr.substring(1);
        }
        //2.进行反转
        String res="";
        for(int i=xstr.length()-1;i>=0;i--){
            res  +=xstr.charAt(i);
        }

        ///3.返回结果
        try{
            return Integer.parseInt(fs+res);
        }catch (Exception e){
            return 0;
        }
    }
}
//上面的方法利用String字符串来进行反转处理。
//方法2:使用取模的方法来处理。
    public int reverse2(int x) {
        int res = 0;
        while(x!=0) {
            //取末尾数字
            int tmp = x%10;
            //判断是否 大于 最大32位整数
            if (res>214748364 || (res==214748364 && tmp>7)) {
                return 0;
            }
            //判断是否 小于 最小32位整数
            if (res<-214748364 || (res==-214748364 && tmp<-8)) {
                return 0;
            }
            res = res*10 + tmp;
            x /= 10;
        }
        return res;
    }
  }
相关推荐
有意义2 小时前
深度拆解分割等和子集:一维DP数组与倒序遍历的本质
前端·算法·面试
xlp666hub3 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
用户726876103373 小时前
解放双手的健身助手:基于 Rokid AR 眼镜的运动计时应用
算法
Wect4 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·typescript
xlp666hub20 小时前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
程序员小崔日记1 天前
大三备战考研 + 找实习:我整理了 20 道必会的时间复杂度题(建议收藏)
算法·408·计算机考研
lizhongxuan1 天前
AI小镇 - 涌现
算法·架构
AI工程架构师1 天前
通常说算力是多少 FLOPS,怎么理解,GPU和CPU为什么差异这么大
算法
祈安_1 天前
Java实现循环队列、栈实现队列、队列实现栈
java·数据结构·算法