码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Day2

时间:2015-08-05 00:31:50      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

Power of Two

技术分享

技术分享
 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 }
View Code

Summary Ranges

技术分享

技术分享
 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 }
View Code

 

LeetCode Day2

标签:

原文地址:http://www.cnblogs.com/luop/p/4703328.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!