博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
306. Additive Number java solutions
阅读量:5146 次
发布时间:2019-06-13

本文共 2044 字,大约阅读时间需要 6 分钟。

Additive number is a string whose digits can form additive sequence.

A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

For example:

"112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8.

1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8

"199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199.

1 + 99 = 100, 99 + 100 = 199

 

Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.

Follow up:

How would you handle overflow for very large input integers?

Credits:

Special thanks to  for adding this problem and creating all test cases.

 

 to see which companies asked this question

1 public class Solution { 2     public boolean isAdditiveNumber(String num) { 3         int len = num.length(); 4         for(int i = 1; i <= len/2; i++){ 5             for(int j = 1; Math.max(i,j) <= len-i-j;j++){ 6                 if(isValid(i,j,num)) return true; 7             } 8         } 9         return false;10     }11     12     public boolean isValid(int i,int j,String num){13         if(num.charAt(0) == '0' && i > 1) return false;14         if(num.charAt(i) == '0' && j > 1) return false;15         String sum;16         Long one = Long.parseLong(num.substring(0,i));17         Long two = Long.parseLong(num.substring(i,i+j));18         for(int s = i+j; s < num.length(); s += sum.length()){19             two = two + one;20             one = two - one;21             sum = two.toString();22             if(!num.startsWith(sum,s)) return false;23         }24         return true;25     }26 }

递归解法:

https://discuss.leetcode.com/topic/50580/java-recursive-simple-dfs-solution

https://discuss.leetcode.com/topic/29856/java-recursive-and-iterative-solutions

 

转载于:https://www.cnblogs.com/guoguolan/p/5666286.html

你可能感兴趣的文章
07动手动脑
查看>>
django知识点总结
查看>>
C++ STL stack、queue和vector的使用
查看>>
OAuth2 .net MVC实现获取token
查看>>
java中XML操作:xml与string互转、读取XML文档节点及对XML节点增删改查
查看>>
使用Reporting Services时遇到的小问题
查看>>
传递事件和传递命令系统···
查看>>
约瑟夫问题
查看>>
Arduino 报错总结
查看>>
树莓派Android Things物联网开发:树莓派GPIO引脚图
查看>>
Database、User、Schema、Tables、Col、Row
查看>>
ckplayer网页播放器简易教程
查看>>
Android Studio 学习(六)内容提供器
查看>>
作业1:求500到1000之间有多少个素数,并打印出来
查看>>
for循环:用turtle画一颗五角星
查看>>
浅谈JavaScript中的eval()
查看>>
操作系统学习(七) 、保护机制概述
查看>>
矩阵快速幂---BestCoder Round#8 1002
查看>>
MySQL建表语句+添加注释
查看>>
DNS练习之正向解析
查看>>