-
Notifications
You must be signed in to change notification settings - Fork 2
/
ContinuesSequenceWithSum.java
48 lines (43 loc) · 1.24 KB
/
ContinuesSequenceWithSum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package org.offer.case41;
/**
* 面试题 41
* 题目二 和为 S 的连续正数序列
* Created by tanc on 17-6-14.
*/
public class ContinuesSequenceWithSum {
/**
* 借鉴题目一的思想,有两个指针,将他们的和与 s 进行比较,然后移动指针
*/
public static void methodOne(int s) {
int small = 1;
int big = 2;
while (small < (s + 1) / 2) {
int result = sumOfSequence(small, big);
if (result < s) {
big++;
} else if (result > s) {
small++;
} else {
printSequence(small, big);
small++;
}
}
}
private static int sumOfSequence(int small, int big) {
int sum = 0;
for (int i = small; i <= big; i++) {
sum += i;
}
return sum;
}
private static void printSequence(int small, int big) {
StringBuilder builder = new StringBuilder();
builder.append("[");
for (int i = small; i <= big; i++) {
builder.append(i).append(",");
}
builder.deleteCharAt(builder.lastIndexOf(","));
builder.append("]");
System.out.println(builder.toString());
}
}