[Leetcode] 2678.Number of Senior Citizens
題目
You are given a 0-indexed array of strings details
. Each element of details
provides information about a given passenger compressed into a string of length 15
. The system is such that:
- The first ten characters consist of the phone number of passengers.
- The next character denotes the gender of the person.
- The following two characters are used to indicate the age of the person.
- The last two characters determine the seat allotted to that person.
Return the number of passengers who are strictly more than 60 years old.
範例
Example 1:
Input: details = [“7868190130M7522”,”5303914400F9211”,”9273338290F4010”]
Output: 2
Explanation: The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old.
Example 2:
Input: details = [“1313579440F2036”,”2921522980M5644”]
Output: 0
Explanation: None of the passengers are older than 60.
解題思路
陣列裡的每一個字串長度都為15,前10個字元為電話,第11個字元為性別(M、F、0),第12、13字元為年齡,最後2個為座位,可以確定都是固定長度。根據題目要求,只需要判斷年齡是否大於60,所以只要取出第12、13個字元做處理就好,抓取字串內的某幾個字元,可以使用C++內建函式substr或是一般陣列。參考 C++ substr() 使用方式
題解
- 用 for 迴圈走訪陣列裡的字串
- 可以使用 substr 取出子字串或是使用陣列方式
- 將字串轉換為整數 int
- 判斷是否大於 60 ,並計數
- 回傳大於 60 總數量
方法一 :
1 |
|
方法二(不使用substr) :
1 |
|