3月6日TopCoder上250分和500分的代碼(我本身寫的)

望你們批評指正: 250分:     題目:On January 1, 2007, a confectioner made several candies. On the last day of each month she allows her children to eat several of those candies. The lifetime of a candy is the number of days between January 1 and the day the candy is eaten, inclusive. For example, the lifetime of a candy eaten on January 31 is 31, and the lifetime of a candy eaten on December 31 is 365 (note that 2007 wasn't a leap year). You are given a int[] eatenCandies, the i-th element of which is the number of candies eaten on the last day of the i-th month of 2007 (January is month 0, February is month 1, etc.). Return the average lifetime of the candies.     代碼:        public class AverageCandyLifetime {     int[] year={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31};     public double getAverage(int[] eatenCandies)     {                         double total = 0;         int nian = 0;         for(int i = 0; i<12;i++)         {             if(eatenCandies[i]>0)             {                 total+=cal(i)*eatenCandies[i];                 nian+=eatenCandies[i];             }         }         total = total/nian;         return total;             }         private double cal(int a)     {         double total = 0;         for(int index=0; index<=a; index++)         {             total+= year[index];         }         return total;     } } 500分     題目:     You are given two Strings s1 and s2. Each string contains some letters and exactly one asterisk ('*'). You must replace each asterisk with a sequence of letters (possibly of zero length). The resulting two strings must be equal. Return the shortest possible resulting string. If it is impossible to make the strings equal, return "impossible" (quotes for clarity) instead.     代碼:     public class TwoStringMasks {     public String shortestCommon(String s1, String s2)     {         char index = '*';         String str;         boolean flag = false;         int length = 0;            if(s1.length()>s2.length())             length = s2.length();         else             length = s1.length();                 char[] str1 = s1.toCharArray();         char[] str2 = s2.toCharArray();                 for(int i=0; i< length; i++)         {             if((s2.charAt(i)!=index)&&(s1.charAt(i)!=index)&&(s2.charAt(i)!=s1.charAt(i)))             {                 flag = true;                 break;             }             if((s1.charAt(i)==index)&&(s2.charAt(i)!=index))                 str1[i] = s2.charAt(i);             if((s2.charAt(i)==index)&&(s1.charAt(i)!=index))                 str2[i] = s1.charAt(i);                     }         if(flag == true)             return "impossible";         if(s1.length()>s2.length())             str = String.copyValueOf(str1);         else             str = String.copyValueOf(str2);         return str;     } }
相關文章
相關標籤/搜索