Escriba un programa para invertir los dígitos de un número entero.
Ejemplos:
Input : num = 12345 Output: 54321 Input : num = 876 Output: 678
Se puede lograr utilizando la forma iterativa o la forma recursiva.
Método iterativo:
Algoritmo:
Input: num (1) Initialize rev_num = 0 (2) Loop while num > 0 (a) Multiply rev_num by 10 and add remainder of num divide by 10 to rev_num rev_num = rev_num*10 + num%10; (b) Divide num by 10 (3) Return rev_num
Ejemplo:
num = 456213
num_rev = 0
num_rev = num_rev *10 + num%10 = 3
num = num/10 = 45621
num_rev = num_rev *10 + num%10 = 20 + 6 = 31
num = num/10 = 4562
num_rev = num_rev * 10 + num%10 = 260 + 5 = 312
num = num/10 = 456
num_rev = num_rev *10 + num%10 = 2650 + 4 = 3126
num = num/10 = 45
num_rev = num_rev *10 + num%10 = 2650 + 4 = 31265
num = num/10 = 4
num_rev = num_rev *10 + num%10 = 2650 + 4 = 312654
num = num/10 = 0
Programa:
PHP
<?php // Iterative function to // reverse digits of num function reversDigits($num) { $rev_num = 0; while($num > 1) { $rev_num = $rev_num * 10 + $num % 10; $num = (int)$num / 10; } return $rev_num; } // Driver Code $num = 456213; echo "Original number is :".$num; echo "\r\n"; echo "Reverse of no. is ", reversDigits($num); ?>
Original number is :456213 Reverse of no. is 312654
Complejidad de tiempo: O(log(n)), donde n es el número de entrada.
Espacio Auxiliar: O(1)
Método recursivo:
PHP
<?php // PHP program to reverse // digits of a number $rev_num = 0; $base_pos = 1; /* Recursive function to reverse digits of num*/ function reversDigits($num) { global $rev_num; global $base_pos; if($num > 0) { reversDigits((int)($num / 10)); $rev_num += ($num % 10) * $base_pos; $base_pos *= 10; } return $rev_num; } // Driver Code $num = 456213; echo "Original number is :".$num; echo "\r\n"; echo "Reverse of no. is ", reversDigits($num); ?>
Original number is :456213 Reverse of no. is 312654
Complejidad de tiempo: O(log(n)) donde n es el número de entrada.
Publicación traducida automáticamente
Artículo escrito por akshitsaxenaa09 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA