Simple C# solution


  • 0
    S
    public class Solution {
        public bool IsAdditiveNumber(string num) 
        {
            if(string.IsNullOrEmpty(num))
                return false;
            for(int i = 1; i<=num.Length/2; i++)
            {
                if(num[0] == '0' && i>1)
                    return false;
                for(int j = 1; num.Length-j-i >= Math.Max(i,j); j++)
                {
                    if(num[i] == '0' && j>1)
                        break;
                    long num1 = long.Parse(num.Substring(0,i));
                    long num2 = long.Parse(num.Substring(i,j));
                    if(IsAdditive(num1, num2, num.Substring(i+j)))
                        return true;
                }
            }
            return false;
        }
        
        private bool IsAdditive(long n1, long n2, string str)
        {
            if(str == string.Empty)
                return true;
            var t = n1+n2;
            if(!str.StartsWith(t.ToString()))
                return false;
            return IsAdditive(n2, t, str.Substring(t.ToString().Length));
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.