华为机试-HJ11 数字颠倒

227 阅读1分钟

题目

image.png

www.nowcoder.com/practice/[a…](www.nowcoder.com/practice/ae…)

我的题解

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str ;
        StringBuilder sb = new StringBuilder();
        while ((str = bf.readLine()) != null) {
            char[] arr = str.toCharArray();
            for (int i = arr.length - 1; i >= 0; i--) {
                sb.append(arr[i]);
            }
        }
        System.out.println(sb);
    }
}

image.png

思路;

1、字符串取变为字符数组、反着拼接

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str ;
        while ((str = bf.readLine()) != null) {
            StringBuffer strb = new StringBuffer(str);
            strb.reverse();
            System.out.println(strb.toString());
        }
    }
}

image.png

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str ;
        while ((str = bf.readLine()) != null) {
            StringBuilder strb = new StringBuilder(str);
            strb.reverse();
            System.out.println(strb.toString());
        }
    }
}

image.png

总结:

1、 reverse() 方法要记牢

            StringBuffer strb = new StringBuffer(str);
            strb.reverse();

            StringBuilder strb = new StringBuilder(str);
            strb.reverse();

高效题解

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        InputStream is = System.in;
        int available = is.available() - 1;
        char[] arr = new char[available];
        while (available-- > 0) {
            arr[available] = (char)is.read();
        }
        String result = String.valueOf(arr);
        System.out.println(result);
    }
}

image.png

总结:

1、排名显示1ms的题解、但是执行12ms肯机器有差异?

2、位运算、先不做了解、回头有时间消化