如何在java中使用数组反转数字?

时间:2016-06-24 17:34:06

标签: java

我正在编写一个代码来反转用户使用java输入的数字。我正在为此目的使用数组。我面临的问题是当我在main函数中调用我的方法时返回数组。

enter image description here

6 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点。取决于是否要使用Java Builtin方法。这是我的部分:

  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("");
    }
    }
    

答案 1 :(得分:0)

我了解您要撤消数组...因此,您可以使用 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++;
    }
}

答案 2 :(得分:0)

您可以使用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());
    }
}

答案 3 :(得分:0)

StringBuilder can do reversals.

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

显然,特殊情况(例如负数)存在一些差距,但我会留下让你解决。这应该是一个很好的起点。

答案 4 :(得分:0)

Java功能强大,但很复杂。

这是一个oneliner。

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.
}

答案 5 :(得分:0)

尝试了一个相对完善的外部库和无阵列解决方案。希望它有所帮助!

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;
}