每日一练(简单)

每日一练

题目:
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1:
输入:x = 123
输出:321
示例 2:

输入:x = -123
输出:-321
示例 3:

输入:x = 120
输出:21
示例 4:

输入:x = 0
输出:0

提示:
-231 <= x <= 231 - 1

第一种解法:(简单)

	public int Reverse(int x) {
	        long n = 0;
	        while(x != 0) {
	            n = n*10 + x%10;
	            x = x/10;
	        }
	        return (int)n==n? (int)n:0;
	}
	
	public static void main(String[] args) {
		Solution so = new Solution();
		System.out.println(so.Reverse(1230));
		

第二种解法:(大神写的,有点绕)

package LiKou;

public class demo2{
	public int reverse(int x){
		if (x == Integer.MIN_VALUE) {
			return 0;
		}
		int neg = x<0 ? -1 : 1;
		x *= neg;
		int ret = 0;
		while(x>0){
			int n = ret;
			n *= 10;
			n += x % 10;
			x /= 10;
			if (n/10 != ret) {
				return 0;
			}
			ret = n;
		}
		return (ret * neg);
	}
	
	public static void main(String[] args) {
		demo2 de = new demo2();
		System.out.println(de.reverse(1534236469));
	}
}

做这道题拓写到字符型,写的有点多

package LiKou;

import java.util.Arrays;

public class Solution {
	public int Reverse(int x) {
		if (x == Integer.MIN_VALUE) {
			return 0;
		}
		if (x % 10 ==0) {
			x = x /10;
		}
		int neg = x<0 ? -1 : 1;
		x *= neg;
		//把int型转为String类型
		String string = Integer.toString(x);
		//转为字符数组
		String[] arr = string.split("");
		if (neg == 1) {
			//用StringBuffer 包裹起来
			StringBuffer stringBuffer = new StringBuffer(string);
			//stringBuffer.reverse() 直接倒叙输出
			System.out.println(stringBuffer.reverse());
		}else{
			StringBuffer stringBuffer = new StringBuffer(string);
			System.out.println("-"+stringBuffer.reverse());
		}
		return 0;
	}
	
	public static void main(String[] args) {
		Solution so = new Solution();
		so.Reverse(1230);
	}
	
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值