package com.coffn.demos;
/**
* 4、键盘录入一个正整数,把它的各个位上的数字倒着排列形成一个新的整数并输出。
例如:12345 数出54321 78760 输出6787(0省去)
*/
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个正整数:");
int num = sc.nextInt();
String str = num+"";
//反转
String reverse =reverse(str);
//统计反转后0的个数
int count = getSum(reverse);
System.out.println();
System.out.println("反转后的数字为:"+getString(reverse,count));
}
//反转
public static String reverse(String str) {
String result = "";
for (int i = str.length()-1; i >= 0; i--) {
result += str.charAt(i);
}
return result;
}
//统计反转之后开头0的个数
public static int getSum(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '0') {
count++;
}else {
break;
}
}
return count;
}
//消0
public static String getString(String str, int count ) {
//用于后面字符串的拼接
String result = "";
for (int i = count; i < str.length(); i++) {
result += str.charAt(i);
}
return result;
}
}
键盘录入一个正整数,把它的各个位上的数字倒着排列形成一个新的整数并输出。 例如:12345 数出54321 78760 输出6787(0省去)
最新推荐文章于 2023-12-03 16:21:50 发布