Write a Java program to reverse an integer number


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. public class Javamathexcercise {
  2. public static void main(String[] args) {
  3. int number =123456789;
  4. int is_positive = 1;
  5. if (number < 0) {
  6. is_positive = -1;
  7. number = -1 * number;
  8. }
  9. int sum = 0;
  10. while (number > 0) {
  11. int r = number % 10;
  12.  
  13. int maxDiff = Integer.MAX_VALUE - sum * 10;
  14. if (sum > Integer.MAX_VALUE / 10 || r > maxDiff)
  15. System.out.println("wrong number");;
  16.  
  17. sum = sum * 10 + r;
  18. number /= 10;
  19. }
  20. System.out.println(is_positive * sum);
  21. }
  22. }

Result

java techstudy.org

     





Related Topics




Popular Posts