day37 445 digital reversal (string processing, simulation)

445. Digital Reversal

Given an integer, please invert the digits of the number to get a new number.

The new number should also satisfy the common form of integers, that is, unless the original number is given as zero, the highest digit of the new number obtained after the inversion should not be zero.

Input format
Input a total of 1 line, 1 integer N.

Output format The
output is 1 line, and 1 integer represents the new number after inversion.

Data range∣
N ∣ ≤ 1 0 9 |N|≤10^9N109
Input sample:

123

Sample output:

321

Input sample:

-380

Sample output:

-83

Ideas:

This is a simple simulation question, we can write the code directly according to the steps of the question. Mainly the following two knowledge points:

  1. With flagmarked positive and negative, to facilitate our unified processing on the digital section.
  2. JavaThe middle Stringclass does not have a reversemethod, but StringBuilderthere is this method in the middle class , so here we need to encapsulate the string into a string StringBuilder, reverse it and then turn it back into a string.

Java code

import java.util.*;

public class Main{
    
    
    public static void main(String[] args){
    
    
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        boolean flag = true;//标记n是否是正数
        if(n < 0) flag = false;
        n = Math.abs(n);
        //注意Java中String类并没有reverse方法,而StringBuilder中有该方法
        //所以这里我们需要先将字符串封装成StringBuilder,反转后再转回字符串
        String str = new StringBuilder(String.valueOf(n)).reverse().toString();
        n = Integer.valueOf(str);
        if(!flag){
    
    
            System.out.println(-n);
        }else{
    
    
             System.out.println(n);
        }
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/YouMing_Li/article/details/114024743