整数反转

整数反转

整数反转:
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:
输入: 123
输出: 321

示例 2:
输入: -123
输出: -321

示例 3:
输入: 120
输出: 21


leetcode官方解答:

class Solution {
public int reverse(int x) {
    int rev = 0;
    while (x != 0) {
        int pop = x % 10;
        x /= 10;
        if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
        if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
        rev = rev * 10 + pop;
    }
    return rev;
}
}

我的解答:

import java.util.*;

//先将输入的整数转化成字符串
//然后转换为字符型数组
//再倒置略去高位上的0
//产生倒置后的字符串,再将字符串转换成整型对象,最后将整形对象变为整数输出。
//注意:字符串转换成整型对象时可能溢出

public class reverse {
public int reverse(int x) {
	if(x == 0)	return 0;
	String str1 = "" + x;
	String str2 = reverseCharArray(str1);
	try {
	Integer integer=Integer.valueOf(str2);
	int num = integer.intValue();
	return num;
	}catch(Exception e) {
		return 0;
	}
}

public static String reverseCharArray(String s) {
	char[] array = s.toCharArray();
	boolean head = true;
	boolean negative = false;
	String reverse = "";
	if(array[0] == '-')	negative = true;	
	for(int i = array.length - 1, j = 0; i >= 0; i--,j++) {
		if(negative) {
			if(array[i] == '0' && head)	continue;	
			if(i == 0)	break;
			reverse += array[i];
			head = false;
		}
		else {
			if(array[i] == '0' && head)	continue;	
			reverse += array[i];
			head = false;
		}
	}
	if(negative)	reverse = '-' + reverse;
	return reverse;
}

public static void main(String[] args) {
	// TODO Auto-generated method stub
		reverse r =new reverse();
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		System.out.print(r.reverse(num));
		sc.close();
}
}

总结与反思

  1. String str1 = "" + x;将整型变量转换成字符串类型;
  2. char[] array = s.toCharArray();将字符串转换为字符型数组;
  3. if(num>Integer.MAX_VALUE) System.out.println("num上溢出");
    if(num<Integer.MIN_VALUE) System.out.println("num下溢出");判断整型数据是否溢出;
AI实战-出租车价格数据集分析预测实例(含20个源代码+65.69 KB完整的数据集) 代码手工整理,无语法错误,可运行。 包括:20个代码,共124.23 KB;数据大小:1个文件共65.69 KB。 使用到的模块: pandas seaborn xgboost matplotlib.pyplot sklearn.preprocessing.RobustScaler sklearn.metrics.mean_absolute_error sklearn.model_selection.GridSearchCV sklearn.model_selection.train_test_split numpy warnings joblib sklearn.set_config sklearn.impute.SimpleImputer sklearn.preprocessing.LabelEncoder sklearn.model_selection.cross_val_score sklearn.preprocessing.StandardScaler sklearn.metrics.r2_score sklearn.metrics.mean_squared_error sklearn.linear_model.LinearRegression sklearn.linear_model.Lasso sklearn.linear_model.Ridge sklearn.neighbors.KNeighborsRegressor sklearn.ensemble.RandomForestRegressor sklearn.ensemble.GradientBoostingRegressor os sklearn.preprocessing.OneHotEncoder sklearn.compose.ColumnTransformer sklearn.pipeline.Pipeline sklearn.tree.DecisionTreeRegressor sklearn.svm.SVR sklearn.neural_network.MLPRegressor bokeh.io.output_notebook bokeh.io.show bokeh.plotting.figure bokeh.layouts.gridplot sklearn.preprocessing.PolynomialFeatures scipy.stats sklearn.metrics.mean_absolute_percentage_error sklearn.ensemble.ExtraTreesRegressor xgboost.XGBRegressor lightgbm.LGBMRegressor sklearn.impute.IterativeImputer statsmodels.stats.outliers_influence.variance_inflation_factor statsmodels.api sklearn.metrics.( plotly.express psynlig.plot_correlation_heatmap bokeh.plotting.show bokeh.plotting.output_notebook catboost.CatBoostRegressor sklearn.linear_model.ElasticNet missingno
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值