如何处理算法?哪种方式首选?

bas*_*sh- 2 java algorithm

所以我正在学习Java并做一些基本算法(对此仍然很新).

假设要求是反转整数,5143使其变为3415.

以下哪一项是更好的方法(或者有更好的方法)?两个不同的函数是reverse()和reverseNum(0忽略反向值的能力):

public class ReverseIntegers {

public static void main(String[] args) {

reverseNum(5143);
reverse(5143);

}

public static void reverse(int number) {

    String numString = Integer.toString(number);
    String result = "";

    char[] cArray = numString.toCharArray();

    for (int i = (cArray.length - 1); i >= 0; i--) {
        result += Character.toString(cArray[i]);    // concatenate the String numbers in reverse order

    }

    System.out.println(Integer.parseInt(result));

}

public static void reverseNum(int number) {

    int numLength = Integer.toString(number).length();

    int[] numArray;
    numArray = new int[numLength];

    int numMod;
    int numModLength;
    int result = 0;


    for (int i = numLength - 1; i >= 0; i--) {

        numMod = (int)(number % Math.pow(10, i + 1));    // eliminate first integer value one by one
        numModLength = Integer.toString(numMod).length();

        while (numModLength > 1) {    // obtain the first integer value of the remainder
            numMod = (numMod / 10); 
            numModLength--;
        }

        numArray[i] = numMod;    // assign the first integer value to the array
    }

    int digits = numArray.length - 1;

    for (int i = 0; i < numArray.length; i++) {    // put numbers in the array in reverse sequence

        result += numArray[i] * Math.pow(10, digits);
        digits--;

    }

    System.out.println(result);

}
}
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 5

第一个函数大致相当于:

String rev = new StringBuilder().append(number).reverse().toString();
System.out.println(Integer.parseInt(rev));
Run Code Online (Sandbox Code Playgroud)

第二个功能(在我看来)很难阅读.由于反复呼叫,它也是非常低效的Integer.toString().

第三种选择(你还没有编写)是一个纯粹基于整数数学的函数,根本不使用字符串.它可能是最有效的.但是,它需要注意如何处理以零结尾的数字.

在我看来,比赛是在第一和第三选择之间; 第二个功能既有缺点,也有两者的优点.

在没有任何进一步信息的情况下,我可能会在这个答案的开头使用代码,并且会用不使用字符串的东西替换它,当且仅当分析应用程序表明它值得做.