【问题标题】:How can I swap the first and last digits of a number in Java using for for-loops?java - 如何使用for循环交换Java中数字的第一位和最后一位?
【发布时间】:2021-11-09 11:12:01
【问题描述】:

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

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

【问题讨论】:

  • 你应该使用任何循环(比如while)还是只允许for?
  • String.replace 如果有变化则返回一个新的String
  • @b.GHILAS 只允许循环。

标签: java loops for-loop numbers swap


【解决方案1】:

使用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

【讨论】:

    【解决方案2】:

    您实际上可以跳过此处的所有循环并使用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()时,函数会返回一个新的String并且不会更新当前的。

    【讨论】:

    • 谢谢,不过按照导师的说法,把数字转成字符串太容易了,所以最好换一种方式。
    【解决方案3】:

    不使用 for 循环更容易。

    static int swapFirstAndLastDigit(int n) {
        return Integer.parseInt(("" + n)
            .replaceFirst("^(-)?(.)(.*)(.)$", "$1$4$3$2"));
    }
    
    public static void main(String[] args) {
        System.out.println(swapFirstAndLastDigit(12345));
        System.out.println(swapFirstAndLastDigit(-54321));
    }
    

    输出:

    52341
    -14325
    

    【讨论】:

    • 这个练习的目的是把第一个数字和最后一个数字交换,而不是把整个数字颠倒过来。
    • @Gas-AndrewChedid 整个数字在哪里颠倒?
    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 2016-06-21
      • 1970-01-01
      相关资源
      最近更新 更多