【题目描述】
【思路】
模拟 。首先先判断正负,再判断在反转的过后开头是否会变成零的数,若为零的数。
import java.util.Scanner;
public class Main{
public static String get(String s){
int len = s.length();
boolean f = false;
//负数要特判
if(s.charAt(0)== '-') {
s = s.substring(1, len);
f = true;
}
StringBuilder sb = new StringBuilder(s);
String ns = sb.reverse().toString();
//高位不能为0
int i = 0;
while( ns.charAt(i) == '0' && i < ns.length() ) i ++;
if(f) return "-" + ns.substring(i, len - 1);
return ns.substring(i, len);
}
public static void main(String args[]){
//|N|≤10^9
Scanner reader = new Scanner(System.in);
String s = reader.next();
System.out.println(get(s));
}
}
看到一种更为简便的巧妙做法:
import java.util.Scanner;
public class Main{
public static void main(String args[]){
//|N|≤10^9
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if(n < 0){
System.out.print("-");
n = -n;
}
int res = 0;
for(; n > 0; n/=10) res = res * 10 + n % 10;
System.out.println(res);
}
}