[JAVA AC 2017/04/06] 10 lines deal overflow with long


  • 0
    S
       I used to suffered Integer overflow pain and cannot find concise way to handle them, until I thought about simple long.
       The key point is change it into normal case since overflow is just a computer game that we can ignore.
    
       ********************************
    
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
    	List<String> ret = new LinkedList<String>();
                if(nums != null && lower <= upper){
      	
        	    long pre = lower-1L, cur = 0;
        	    for(int i = 0; i <= nums.length; i++){
        		    cur = (i == nums.length ? upper+1L : nums[i]);
        		    if(cur - pre > 1){
        			ret.add(getRange(pre+1L, cur-1L));
        		    }
        		    pre = cur;
        	    }
                }      
               return ret;
         }
    
         private static String getRange(long from, long to) {
    	   return from == to ? String.valueOf(from) : from + "->" + to;
         }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.