English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste programa, você aprenderá a usar o loop while e o loop for para inverter números em Java.
public class ReverseNumber { public static void main(String[] args) { int num = 1234, reversed = 0; while(num != 0) { int digit = num % 10; reversed = reversed * 10 + digit; num /= 10; } System.out.println("Número invertido: ", + reversed); } }
When running the program, the output is:
Número invertido: 4321
Neste programa, o loop while é usado para inverter o número nas seguintes etapas:
Primeiro, divida num por10O resto é armazenado na variável digit. Agora, digit contém o último dígito de num, ou seja4E, em seguida, multiplique digit por10Depois de multiplicar, adicione-o à variável invertida. Multiplique10Um novo local será adicionado ao número invertido. A décima parte multiplicada por10Pode obter o décimo dígito, a décima parte pode obter a porcentagem, e assim por diante. Neste caso, reversed contém 0 * 10 + 4 =4.
Depois disso, num dividido por10Portanto, agora apenas contém os três primeiros dígitos:123.
Após a segunda iteração, digit é igual a3Portanto, reversed é igual a4 * 10 + 3 = 43e num= 12
Após a terceira iteração, digit é igual a2Portanto, reversed é igual a43 * 10 + 2 = 432e num= 1
Após a quarta iteração, digit é igual a1Portanto, reversed é igual a432 * 10 +1 = 4321e num= 0
Agora num= 0, portanto a expressão de teste num != 0 falhou e o loop while foi encerrado. reversed já contém o número invertido4321.
public class ReverseNumber { public static void main(String[] args) { int num = 1234567, reversed = 0; for(;num != 0; num /= 10) { int digit = num % 10; reversed = reversed * 10 + digit; } System.out.println("Reversed Number: ", + reversed); } }
When running the program, the output is:
Reversed Number: 7654321
In the above program, the while loop is replaced by the for loop, where:
Without using the initialization expression
The test expression remains unchanged (num != 0)
Update/The increment expression contains num /= 10.
Therefore, after each iteration, the update expression will run, thereby deleting the last digit num.
When the for loop exits, reversed will contain the opposite numbers.