007 easy

4/29/2015

Meet a very serious problem: overflow when reversed.

As the spoilers say, return 0 when the reversed number overflows.

Solution: 1) use LONG type to store the overflowed result. 2) add judgement of overflow or not before output it

Algorithm 1

(Came by my first thought)

Meet another problem of dealing with overflow number. The problem came with j.

Problem: j is the number 1,10,100… 1,000,000,000. When dealing with the first digit of 3(like 1 when x=1,000,000,003) j=1,000,000,000 from the last loop. but in this loop, sum will be added to 3,000,000,000, theoretically. However, because j overflows as an integer, the result sum in this loop messed up.

Two solutions:
S1: set j as long type
S2: sum=(long ) array[i]j+sum; OR sum=array[i](long) j+sum; use forced type transfer
package happynumber;

public class ReverseInteger {
    public static int reverse (int x) {

        int i;i=0;
        //long type is for compare. Only larger range can compare Max and Min Integer
                long sum=0;
        int[] array=new int[33];
        int number;

        number=x;
        if(x<0) number=-x;
        System.out.println(number);

        System.out.println(number);
        while(number!=0) {
            array[i]=number%10;
            System.out.println(array[i]);
            number=number/10;
            i++;

        }

        long j;j=1;     
        i=i-1;

        for(;i>=0;i--){
            sum=array[i]*j+sum;
            System.out.println(sum);

            j=j*10;
            System.out.println(j);
        }


        if(x<0) sum=-sum;

        System.out.println("original result");
        System.out.println(sum);

        if(sum>Integer.MAX_VALUE || sum<Integer.MIN_VALUE) {
            System.out.println("overflow");
            return 0;
        }
        else {

            System.out.println((int)sum);
            return (int) sum;

        }


    }
    public static void main(String args[]) {
        int y=0;
        y=reverse(-1000000003);
    }

}

Algorithm 2: change about calculating result algorithm

package happynumber;

public class ReverseInteger2 {
        public static int reverse (int x) {

            long result,number;

            result=0;
            number=x;
            if(x<0) number=-number;
            while(number!=0) {
                result=result*10+number%10;
                number=number/10;
            }

            if(x<0) result=-result;

            System.out.println("original result");
            System.out.println(result);

            if(result>Integer.MAX_VALUE || result<Integer.MIN_VALUE){
                System.out.println(0);
                return 0;
            }
            else {
                System.out.println((int)result);
                return (int) result;
            }



        }
        public static void main(String args[]) {
            int y=0;
            y=reverse(1000000003);
        }


}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页