只有形如1000这种数需要变成999,其它都是把前半段反过来拷到后半段:
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String s = sc.nextLine(); if(s.length() <= 1){ System.out.println(s); return; } if(f(s)){ //只有形如1000这种数需要变成999 String r = ""; while(r.length() < s.length() - 1) r += "9"; System.out.println(r); return; } StringBuilder str = new StringBuilder(s); StringBuilder sb = new StringBuilder(s).reverse(); int n = s.length(); str.replace(n/2, n, sb.substring(n/2, n));//把前半段反过来拷到后半段 System.out.println(str); } static boolean f(String s){ //判断是不是形如1000这种数 boolean flag = true; if(s.charAt(0) != '1') flag = false; if(s.charAt(0) == '1'){ for(int i = 1; i < s.length(); ++i){ if(s.charAt(i) != '0'){ flag = false; break; } } } return flag; } }