Old Top Coder riddle: Making a number by inserting +

后端 未结 6 1550
借酒劲吻你
借酒劲吻你 2021-02-06 05:41

I am thinking about this topcoder problem.

Given a string of digits, find the minimum number of additions required for the string to equal some target n

6条回答
  •  一个人的身影
    2021-02-06 05:48

    I haven't given it much thought yet, but if you scroll down you can see a link to the contest it was from, and from there you can see the solvers' solutions. Here's one in C#.

    using System; 
    using System.Text; 
    using System.Text.RegularExpressions; 
    using System.Collections; 
    
    public class QuickSums { 
        public int minSums(string numbers, int sum) { 
            int[] arr = new int[numbers.Length]; 
        for (int i = 0 ; i < arr.Length; i++)       
          arr[i] = 0; 
    
        int min = 15; 
    
        while (arr[arr.Length - 1] != 2)     
        { 
          arr[0]++; 
          for (int i = 0; i < arr.Length - 1; i++) 
            if (arr[i] == 2)  
            { 
              arr[i] = 0; 
              arr[i + 1]++; 
            } 
    
          String newString = ""; 
          for (int i = 0; i < numbers.Length; i++) 
          { 
            newString+=numbers[i]; 
            if (arr[i] == 1) 
              newString+="+"; 
          } 
    
          String[] nums = newString.Split('+'); 
          int sum1 = 0; 
          for (int i = 0; i < nums.Length; i++) 
            try  
            { 
              sum1 += Int32.Parse(nums[i]); 
            } 
            catch 
            { 
            } 
    
          if (sum == sum1 && nums.Length - 1 < min) 
            min = nums.Length - 1; 
        } 
    
        if (min == 15) 
          return -1; 
    
        return min; 
      } 
    
    } 
    

提交回复
热议问题