Java 算法 CodeWar——Day 1

Code War

  • code war honor 27
  • uestc position 58

quesetion 1

Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word.

Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.

Example:

Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"
Note that the Java version expects a return value of null for an empty string or null.

translation 1

給一個初始的字符串,對于該字符串的每個單詞的首字母轉換為大寫并返回,當傳入字符串為空字符串(即"")或者傳入?yún)?shù)為null時,返回null。

public class JadenCase {

  public String toJadenCase(String phrase) {
    if(phrase == null || phrase.length() == 0 )
    {
        return null;
    }

    char[] str = phrase.toCharArray();
    str[0] = Character.toUpperCase(str[0]);
    for (int i = 0; i < str.length ; i++ )
    {
        if(str[i] == ' ')
        {
            str[i+1] = Character.toUpperCase(str[i+1]);
        }
    }
    return new String(str);
  }
}
  1. 在判斷參數(shù)類型時,如果需要判斷傳入的參數(shù)是否為null, 則必須首先判斷是否為null,再判斷其他條件,反例: phrase.length() == 0 || phrase == null,在判斷這個條件時,如果phrase為null,這是首先判斷其長度,就會出錯。
  2. 字符串轉化為字符串數(shù)組時,用str.CharArray();
  3. 字符大小寫轉化:Character.toUpperCase(char c)、 Character.toLowerCase(char c)
  4. 字符數(shù)組轉換為字符串 new String(char c[])

question 2

In a small town the population is p0 = 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater or equal to p = 1200 inhabitants?

At the end of the first year there will be:
1000 + 1000 * 0.02 + 50 => 1070 inhabitants

At the end of the 2nd year there will be:
1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer)

At the end of the 3rd year there will be:
1141 + 1141 * 0.02 + 50 => 1213

It will need 3 entire years.

More generally given parameters:

p0, percent, aug (inhabitants coming or leaving each year), p (population to surpass)

the function nb_year should return n number of entire years needed to get a population greater or equal to p.

aug is an integer, percent a positive or null number, p0 and p are positive integers (> 0)

Examples:
nb_year(1500, 5, 100, 5000) -> 15
nb_year(1500000, 2.5, 10000, 2000000) -> 10
Note: Don't forget to convert the percent parameter as a percentage in the body of your function: if the parameter percent is 2 you have to convert it to 0.02.

translation 2

某個區(qū)域的人口初始為p0,每年以 百分之percent的速度增加,另外每年還會遷移過來aug個人,編程實現(xiàn)函數(shù),返回幾年后人口會達到p。

class Arge {
    
    public static int nbYear(int p0, double percent, int aug, int p) {
        int sum;
        percent = percent*0.01;
        for(int i = 1; ; i++ )
        {
            sum = (int)(p0 + p0 * percent + aug);
            if( sum >= p)
            {
                return i;
            }
            p0 = sum;
        }
    }
}
  1. 強制轉換 (int)float a;

question 3

Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.

For example:

 persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
                      // and 4 has only one digit

 persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126,
                       // 1*2*6 = 12, and finally 1*2 = 2

 persistence(4) == 0 // because 4 is already a one-digit number

translation 3

實現(xiàn)一個函數(shù)persistence, 傳入一個正整數(shù)參數(shù),把參數(shù)的每個數(shù)字相乘,得到的積如果不是個位數(shù),那么重復上述操作,繼續(xù)乘,如果是個位數(shù),那么返回計算的次數(shù)(即重復了多少次上述操作)

class Persist {
  public static int persistence(long n) {
    char str[] = (n+"").toCharArray();
        int time=0;
        while(str.length > 1)
        {
            int temp = 1;
            int[] key = new int[str.length];
            for(int i = 0; i < str.length; i++)
            {
                key[i] = Integer.parseInt(String.valueOf(str[i]));
                temp = key[i] * temp;
            }
            str = (temp+"").toCharArray();
            time++;
            if(temp < 10)
            {
                break;
            }

        }

        return time;
  }
}
  1. 數(shù)字轉化為字符串 可使用如下方式 int + ""
  2. Java中數(shù)組的創(chuàng)建方法: int[] arr = new int[length];
  3. 字符轉化為數(shù)字:Integer.parseInt(String.valueOf(char c))
    即把'2'轉換為數(shù)字2,而強制轉換(int)char c;是把對應字符轉化為對應的ascii碼值

question 4

Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters,

each taken only once - coming from s1 or s2.

Examples:
a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq" longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz" longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"

translation 4

給定兩個字符串,統(tǒng)計出現(xiàn)的字母并按照字母表的順序排序

public class TwoToOne {
    
    public static String longest (String s1, String s2) {
       char[] str = (s1+s2).toCharArray();
        int[] key = new int[26];
        char[] aim = new char[26];
        for(int i = 0; i < str.length; i++)
        {
            key[(int)str[i] - 97] = 1;
        }
        int i = 0;
        for(int j = 0; j < 26; j++)
        {
            if(key[j] == 1)
            {
                aim[i] = (char)(j+97);
                i++;
            }
        }
        char[] re = new char[i];
        System.arraycopy(aim, 0, re, 0,i);
        return new String(re);
    }
}
  1. 字符串拼接 str1 + str2;
  2. 數(shù)組復制函數(shù)
    arraycopy(@NotNull Object src, int srcPos,@NotNull Object dest,int destPos,int length)
    參數(shù) src 源數(shù)組,srcPos 源數(shù)組復制起點,dest 目標數(shù)組,destPos 目標數(shù)組開始位置,復制長度,

對應代碼鏈接,歡迎fork和star

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,100評論 0 23
  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,921評論 0 33
  • 唐鶴升 昨天,一位家鄉(xiāng)的朋友發(fā)給我一份倡議書,說家鄉(xiāng)在村村通水泥路的施工進程中,因資金不足,無法正常完工.號召我...
    唐鶴升閱讀 350評論 0 1
  • 大塔 二塔 三塔 遼中京三塔 說是在很久以前在塞外的漠南,有一大片肥沃的土地“現(xiàn)在是寧城縣大明鎮(zhèn)”后有九頭山,前有...
    二斗八閱讀 2,533評論 15 15
  • 寶貝,今天是你離開的第十天,一切都像是夢一場。 夜深人靜的時候,我腦海里反復浮現(xiàn)在醫(yī)院里的場景,我們朝夕相處九個月...
    畫樓西畔閱讀 380評論 0 0

友情鏈接更多精彩內(nèi)容