gpt4 book ai didi

java - 使用for循环java逆向生成一个数字

转载 作者:行者123 更新时间:2023-12-02 10:32:48 25 4
gpt4 key购买 nike

所以我尝试使用 for 循环反转 java 中的数字,我得到了正确的值,但我不确定这是否是最好的方法。

package forloops;
/*
% prints the last number in the sequence
/ prints every number except for the last one
*/
public class modulusForLoops {
public static void main(String[]args) {
int orig = 123456789;
int num = orig;
for (int i = 0; i < 1; i++) {
num = orig % 10; //9
int secondDigit = orig / 10; //12345678
int secondDigitPrinted = secondDigit % 10; //8
int thirdDigit = secondDigit / 10; //1234567
int thirdDigitPrinted = thirdDigit % 10; //7
int fourthDigit = thirdDigit / 10; //123456
int fourthDigitPrinted = fourthDigit % 10; //6
int fifthDigit = fourthDigit / 10; //12345
int fifthDigitPrinted = fifthDigit % 10;
int sixthDigit = fifthDigit / 10; //1234
int sixthDigitPrinted = sixthDigit % 10; //4
int seventhDigit = sixthDigit / 10; //123
int seventhDigitPrinted = seventhDigit % 10; //3
int eigthDigit = seventhDigit / 10; //12
int eigthDigitPrinted = eigthDigit % 10; //2
int lastDigit = eigthDigit / 10; //1
System.out.println(orig + " reversed is " + num + secondDigitPrinted + thirdDigitPrinted + fourthDigitPrinted + fifthDigitPrinted + sixthDigitPrinted + seventhDigitPrinted + eigthDigitPrinted + lastDigit);
}
}
}

最佳答案

您可以简单地将其转换为 String 并使用 java.lang.StringBuilder 反转字符串。

int orig = 123456789;
String numString = Integer.toString(orig);
String reversed = "";
for (int i = numString.length() - 1; i >= 0; i--) { // loop through the string from back to front
reversed += numString.charAt(i); // add each character to the resulting string
}
System.out.println(reversed);

或者

int orig = 123456789;
String numString = Integer.toString(orig); // convert int to String
String reversed = new StringBuilder(numString).reverse().toString(); // reverse string
System.out.println(reversed);

关于java - 使用for循环java逆向生成一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53511663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com