如何使用 for 循环交换 Java 中数字的首位和末位?

How can I swap the first and last digits of a number in Java using for for-loops?

这是我的代码(不工作),没有使用循环。

System.out.println("Enter a five digit number: ");
int number = scanner.nextInt();

int lastDigit = number % 10;            //by using the % operator, we are able to retrieve the last digit of the number

int firstDigit = number;
while(firstDigit > 9) {
    firstDigit /= 10;
}
//======================================================//
System.out.println("The first digit of the number is " + firstDigit);
System.out.println("The last digit of the number is " + lastDigit);

String string = Integer.toString(number);

char first = string.charAt(0);
char last = string.charAt(string.length() - 1);

string.replace(first, last);
string.replace(last, first);

System.out.println(string);

你实际上可以跳过这里的所有循环并使用 strings.

像这样:

public static int swapNr(int nr)
{
    String nrStr = String.valueOf(nr); // Turning our nr into a String

    char[] charArr = nrStr.toCharArray(); // Getting the char Array out of it

    char firstNr = charArr[0]; // Getting the first character
    char lastNr = charArr[charArr.length - 1]; // Getting the last one
    
    // Changing their places
    charArr[0] = lastNr;
    charArr[charArr.length - 1] = firstNr;
    
    return Integer.parseInt(String.valueOf(charArr)); // Turning the String into an Integer again
}

String.replace() 不是更改 String 中特定字符位置的正确方法。而且你必须知道 Strings 是不可变的,这意味着当你调用 .replace() 时,函数 returns 一个新的 String 而不会更新当前的

不使用 for 循环更容易。

static int swapFirstAndLastDigit(int n) {
    return Integer.parseInt(("" + n)
        .replaceFirst("^(-)?(.)(.*)(.)$", ""));
}

public static void main(String[] args) {
    System.out.println(swapFirstAndLastDigit(12345));
    System.out.println(swapFirstAndLastDigit(-54321));
}

输出:

52341
-14325

你可以完全不用循环,只使用算术:

    public static int swap(int v) {
        final int lastDigit = v % 10;
        // the number of digits - 1 (1 digit = 0, 2 digits = 1, ...)
        final int digitsMinusOne = (int) Math.floor(Math.log10(v));
        // the multiplier used for getting/setting the first digit
        // examples:
        // 1234, digitsMinusOne=3, multiplier = 10^3 = 1000
        // 827382, digitsMinusOne=5, multiplier = 10^5 = 100000
        final int multiplier = (int) Math.pow(10, digitsMinusOne);
        // the first digit can be retrieved by dividing by the multiplier
        // for example:
        // 1234 / 1000 = 1
        // 827382 / 100000 = 8
        final int firstDigit = v / multiplier;
        

        // replacing the last digit with the first digit
        v = (v - (v % 10)) + firstDigit;
        // replacing the first digit with the last digit
        v = (v - (firstDigit * multiplier)) + (lastDigit * multiplier);

        return v;
    }

一种使用for循环交换数字的方法:

static int swapDigits(int x) {
    System.out.print(x + " -> ");
    int sign = Integer.signum(x);
    x *= sign;  // invert negative number if necessary

    int last = x % 10;
    int n = x / 10;
    int s = 0;       // sum for the digits in the middle
    for (int p = 1; n > 10; n /= 10, last *= 10, p *= 10) {
        s += p * (n % 10);
    }
    return sign * (10 * (last + s) + n); // restore the sign and get swapped digits
}

测试:

System.out.println(swapDigits(12345));  // 12345 -> 52341
System.out.println(swapDigits(607081)); // 607081 -> 107086
System.out.println(swapDigits(98760));  // 98760 -> 8769  // leading 0 lost
System.out.println(swapDigits(-12345)); // -12345 -> -52341