簡體   English   中英

如何在java中使用數組反轉數字?

[英]how to reverse a number using array in java?

我正在編寫一個代碼來反轉用戶使用 java 輸入的數字。 我為此使用了一個數組。 我面臨的問題是當我在主函數中調用我的方法時返回數組。

在此處輸入圖片說明

我知道您想反轉數組...因此,您可以使用ArrayUtils.reverse

ArrayUtils.reverse(int[] array)

例如,您可以執行以下操作:

public static void main(String[] arg){
    int[] arr = { 1,2,3,4,5,6};
    ArrayUtils.reverse(arr);
    System.out.println(Arrays.toString(arr));
    // Prints: [6, 5, 4, 3, 2, 1]
}

但是,如果你想自己寫反向代碼,如果你查看 ArrayUtils.reverse 的源代碼,你可以找到 Apache 家伙是如何做到的。 這里的實現:

public static void reverse(int[] array) {
    if (array == null) {
        return;
    }
    int i = 0;
    int j = array.length - 1;
    int tmp;
    while (j > i) {
        tmp = array[j];
        array[j] = array[i];
        array[i] = tmp;
        j--;
        i++;
    }
}

有很多方法可以做到。 取決於您是否要使用 Java 內置方法。 這是我的部分:

  1. 使用 ListIterator 反轉 int 數組:

     public class ReverseAListWithoutInbuiltMethods { public static void main(String[] args) { int[] arr={12, 4, 34, 7, 78,33, 20}; display(arr); int[] rev=reverse(arr); display(rev); } private static void display(int[] arr){ for(int i=0;i<arr.length;i++){ System.out.print(" "+arr[i]); } System.out.println(""); } private static int[] reverse(int[] arr){ List<Integer> list=new ArrayList<Integer>(); for(int a:arr){ list.add(a); } int[] rev=new int[arr.length]; int j=0; ListIterator<Integer> listI=list.listIterator(arr.length); while(listI.hasPrevious()){ rev[j]=listI.previous(); j++; } return rev; } }
  2. 僅通過 for 循環反轉:

     public static void main(String[] args) { /* create a new string */ StringBuilder s = new StringBuilder("GeeksQuiz"); System.out.println(" ************* REVERSED STRING IS **************"); char[] c2=reverseForLoop(s); for (int i = 0; i < c2.length; i++) { System.out.print(c2[i]); } } private static char[] reverseForLoop(StringBuilder sb) { char[] str = sb.toString().toCharArray(); int n = str.length; char[] charNew = new char[n]; int j = 0; for (int i = n - 1; i >= 0; i--) { charNew[j] = str[i]; j++; } return charNew; }
  3. 使用交換方法反轉:

     private static char[] reverse2(StringBuffer sb) { char[] str=sb.toString().toCharArray(); int n = str.length; for (int i = 0; i < n / 2; i++) { swap(str, i, n - 1 - i); } return str; } private static void swap(char[] charA, int a, int b) { char temp = charA[a]; charA[a] = charA[b]; charA[b] = temp; }
  4. 使用堆棧實現反轉字符串:

     public class StackForStringReverse { public static void main(String[] args) { /*create a new string */ StringBuffer s= new StringBuffer("GeeksQuiz"); /*call reverse method*/ reverse(s); /*print the reversed string*/ System.out.println("Reversed string is " + s); } private static void reverse(StringBuffer str) { int n=str.length(); MyStack obj=new MyStack(n); // Push all characters of string // to stack int i; for (i = 0; i < n; i++) obj.push(str.charAt(i)); // Pop all characters of string and put them back to str for (i = 0; i < n; i++) { char ch = obj.pop(); str.setCharAt(i,ch); } } } class MyStack{ int size; char[] a; int top; public MyStack(int n) { top=-1; size=n; a=new char[size];//{'1','f','f','f'}; } public boolean isEmpty() { return top<0; } /** * Insert data into Stack if it's not full*/ public void push(char c) throws IllegalArgumentException{ if(top>=size) { throw new IllegalArgumentException("Stack overflow."); } a[++top]=c; } public char pop() { if(top<0) { throw new IllegalArgumentException("Stack underflow."); } char x=a[top--]; return x; } public void clear() { while(top>0) { top--; size=top; } } /** * Display the data inserted */ public void display() { for(int i=0;i<a.length;i++) { System.out.print(a[i]); } System.out.println(""); } }

您可以使用 StringBuilder 做到這一點:

public class Main {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println(getReverse(s.nextInt()));
    }

    public static int getReverse(int a){
        StringBuilder sb = new StringBuilder();
        sb.append(String.valueOf(a));
        sb = sb.reverse();
        return Integer.parseInt(sb.reverse().toString());
    }
}

StringBuilder 可以進行反轉。

String reverseNumber(Number n) {
    String numStr = n.toString();
    StringBuilder reverser = new StringBuilder(numStr);
    reverser.reverse();
    return reverser.toString();
}

顯然,對於特定情況(例如負數),這里存在一些差距,但我會將其留給您解決。 這應該是一個很好的起點。

Java 功能強大,但很復雜。

這是它的單線。

public static void main(String[] args) {
    int n = 123; 
    int reversed_n = (int) Integer.valueOf( // 5.) cast back to an int. 
        new StringBuilder(
            Integer.toString(n)             // 1.) Make the integer a String. 
        )                                   // 2.) load that string to a String builder.
            .reverse()                      // 3.) reverse the string.
                .toString()));              // 4.) go back to a string.
}

嘗試使用文檔相對完備的外部庫和無陣列解決方案。 希望有幫助!

int reverseNumber(int inputNum)
{
    String numString = Integer.toString(inputNum);
    int numLength = numString.length();

    int finalReversedNumber = 0;

    /*
     * Goes through the input number backwards, and adds the digit (with it's new value) to the final number.
     *  This is accomplished by multiplying the current number by 10 to the power of the index i, which corresponds
     *  to the current digit value of the number.
     * i the index counter, goes from the length of the input number (not inclusive) to 0 (inclusive)
     */
    for(int i=numLength-1; i>=0; i--)
    { 
        int currentNum = Integer.parseInt(String.valueOf(numString.charAt(i)));
        int valueInFinalNum = currentNum * (int)Math.pow(10, i); // i.e. a 5 in the thousands digit is actually 5000
        finalReversedNumber += valueInFinalNum;
    }

    return finalReversedNumber;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM