Huawei Online Programming Questions Series-11-Number Reversed


Problem Description:
Problem Description

1. The question involves knowledge points.

  • Reverse order of integers
  • StringBuffer.reverse()

2. Solve it yourself.

  • Solution 1: Print in the form of the lowest digit of the integer each time.
package com.chaoxiong.niuke.huawei;

import java.util.Scanner;

/**
 * Create by tianchaoxiong on 18-4-9.
 */
public class HuaWei_11_2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            int key = scanner.nextInt();
            getResult(key);
        }
    }

    private static void getResult(int key) {
        int []intArr = new int[9];
        int intArrIndex = 0;
        while (key>0){
            intArr[intArrIndex] = key%10;
            intArrIndex++;
            key = key/10;
        }
        for(int i=0;i<intArrIndex;i++){
            System.out.print(intArr[i]);
        }
    }
}
  • Solution 2: Convert integers to characters, and then print them in reverse.
package com.chaoxiong.niuke.huawei;

import java.util.Scanner;

/**
 * Create by tianchaoxiong on 18-4-9.
 */
public class HuaWei_11_2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            int key = scanner.nextInt();
            getResult(key);
        }
    }
    private static void getResult(int key) {
        String strKey = key+"";
        int len = strKey.length();
        for(int i =0;i<len;i++){
            System.out.print(strKey.charAt(len-1-i));
        }
        System.out.println();
    }
}
  • Solution 3: Integer to character conversion stringbuilder. Call the stringBuilder.reverse()method to print.
package com.chaoxiong.niuke.huawei;

import java.util.Scanner;

/**
 * Create by tianchaoxiong on 18-4-9.
 */
public class HuaWei_11_3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            int key = scanner.nextInt();
            getResult(key);
        }
    }
    private static void getResult(int key) {
        System.out.println(new StringBuffer(key+"").reverse());
    }
}

3. Quality answers.

null

4. Summary of this question.

There are three most common ways to reverse the order
of integers - use the form of an integer every time %10 and then/10.
- Convert to a string, traverse from the last one.
- Convert to a string, and then convert StringBuffer/ StringBuildercall sb.reverse()direct reverse order.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325377945&siteId=291194637