标签:
1 /** 2 * LeetCode: Power of Two 3 * Given an integer, write a function to determine if it is a power of two. 4 * 5 * @author LuoPeng 6 * @time 2015.8.3 7 * 8 */ 9 public class PowerOfTwo { 10 11 public boolean isPowerOfTwo(int n) { 12 13 boolean result = false; 14 if ( n == 1) { 15 result = true; 16 } else if ( n > 1) { 17 while ( n % 2 == 0) { 18 n = n/2; 19 } 20 result = (n==1)?true:false; 21 } 22 return result; 23 } 24 25 }
1 /** 2 * LeetCode: Summary Ranges 3 * Given a sorted integer array without duplicates, return the summary of its ranges. 4 * For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 5 * 6 * If the next value is equal to the current value+1, then the next value should be merged together. 7 * Input:[0, 1, 5, 7, 8]; output:["0->1", "5", "7->8" 8 * Input:[3, 5, 6, 7, 9]; output:["3", "5->7", "9"] 9 * 10 * @author LuoPeng 11 * @time 2015.8.4 12 * 13 */ 14 public class SummaryRanges { 15 16 /** 17 * 18 * @param nums 19 * @return 20 */ 21 public List<String> summaryRanges(int[] nums) { 22 23 if ( nums == null) {return null;} 24 25 List<String> result = new ArrayList<String>(); 26 if ( nums.length != 0) { 27 String temp = null; 28 int length = nums.length; 29 int start = 0; 30 for ( int i = 1; i < length; i++) { 31 if ( nums[i] - nums[i-1] != 1) { 32 if ( i == start+1) { 33 // the value should be itself 34 temp = "" + nums[start]; 35 } else { 36 temp = nums[start] + "->" + nums[i-1]; 37 } 38 result.add(temp); 39 start = i; 40 } 41 } 42 43 // the last element 44 if ( length == start+1) { 45 temp = "" + nums[start]; 46 } else { 47 temp = nums[start] + "->" + nums[length-1]; 48 } 49 result.add(temp); 50 } 51 52 return result; 53 54 } 55 56 }
标签:
原文地址:http://www.cnblogs.com/luop/p/4703328.html