GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/src/AdditiveNumber.java at master · LeBW/leetcode

Expand file tree

/

AdditiveNumber.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
57 lines (54 loc) · 1.58 KB
/

AdditiveNumber.java

Copy path

File metadata and controls

57 lines (54 loc) · 1.58 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
49
50
51
52
53
54
55
56
57
/**
* 306. Additive Number
* @author LBW
*/
public class AdditiveNumber {
public boolean isAdditiveNumber(String num) {
int len = num.length();
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (isAdditive(num, i, j))
return true;
}
}
return false;
}
private boolean isAdditive(String num, int i, int j) {
int cur = j + 1; // current index
if (cur >= num.length())
return false;
long num1 = getNumber(num, 0, i);
long num2 = getNumber(num, i + 1, j);
if (num1 == -1 || num2 == -1)
return false;
long sum = num1 + num2;
while (cur < num.length()) {
if (num.substring(cur).startsWith(Long.toString(sum))) {
num1 = num2;
num2 = sum;
cur += Long.toString(sum).length();
sum = num1 + num2;
}
else {
return false;
}
}
return true;
}
// return -1 when starts with '0'
private long getNumber(String num, int l, int r) {
if (num.charAt(l) == '0' && r > l)
return -1;
int i = l;
long sum = 0;
while (i <= r) {
sum = sum * 10 + num.charAt(i) - '0';
i++;
}
return sum;
}
public static void main(String[] args) {
AdditiveNumber additiveNumber= new AdditiveNumber();
System.out.println(additiveNumber.isAdditiveNumber("111122335588143"));
}
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.