Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

integer - Java Int(Why returning 0 when number is within range)

Thank you for your time!

  1. for value upto 2147483641 code is working fine after that it is returning 0(why).. as per my understanding program should return 0 only when overflow occurs.. (for -2147483648 and 2147483647 ) not for value falling in the range.

  2. Also please share any link for leading zero number reversal.. I could not find any online.

     public class ReverseDigit {
         public int reverse(int integer) {
             boolean negflag=false;
             if(integer<0){
                       negflag=true;
                       integer=integer*-1;
                           }
             int rev=0;
             int rem=0;
             while(integer!=0){
                      rem=integer%10;
                      int newrev= rev*10+rem;
                      if((newrev-rem)/10!=rev){
                      return 0;
                                               }
              else{
    
                      rev=newrev;
                  }
                      integer=integer/10;
         }
                       return  rev = negflag?rev*-1:rev;
     }
    
     public static void main(String[] args) {
                 ReverseDigit rd = new ReverseDigit();
                 System.out.println(rd.reverse(**2147483642**));
    
    
     }
    

    }

question from:https://stackoverflow.com/questions/65912660/java-intwhy-returning-0-when-number-is-within-range

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is happens because the reversed number of 2147483642 is 2463847412, and this number is greater then Intrgre.MAX_VALUE which is 2147483647, so the number became less than 0. This is happens to 2147483623 too, because his reversed number is 3263847412, and this number is greater then Intrgre.MAX_VALUE. To fix that, I see two possible solutions:

  1. Use long instead of int.
  2. Rewrite the method to work with String, because you aren't really do any calculations (You can use string.charAt(int index) to get the digits one bt one).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...