[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.

2678.Number of Senior Citizens

範例

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() 使用方式

題解

  1. 用 for 迴圈走訪陣列裡的字串
  2. 可以使用 substr 取出子字串或是使用陣列方式
  3. 將字串轉換為整數 int
  4. 判斷是否大於 60 ,並計數
  5. 回傳大於 60 總數量

方法一 :

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int countSeniors(vector<string>& details) {

int count = 0;
for(const string &s : details) {
string sub_str = s.substr(11, 2);
if(stoi(sub_str) > 60)
count++;
}
return count;
}
};

方法二(不使用substr) :

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int countSeniors(vector<string>& details) {

int res = 0;
for(int i = 0; i < details.size(); i++){
int age = ((details[i][11] - '0') * 10 + details[i][12] - '0');
res += (age > 60);
}
return res;
}
};

[Leetcode] 2678.Number of Senior Citizens
http://example.com/2024/08/01/Leetcode/Array/2678_Number_of_Senior_Citizens/
Author
Jay
Posted on
August 1, 2024
Updated on
August 2, 2024
Licensed under