Compare commits

...

2 Commits

Author SHA1 Message Date
0c024b85fd Merge branch 'main' of git.flyaha.top:yaha/leetcode 2023-06-09 14:48:38 +08:00
04295f0825 把字符串转换成整数 2023-06-09 14:48:20 +08:00
3 changed files with 39 additions and 6 deletions

View File

@ -45,6 +45,15 @@ public:
* @return * @return
*/ */
std::string reverse_left_words(std::string s, int n); std::string reverse_left_words(std::string s, int n);
/**
* Offer 67.
*
* @url https://leetcode.cn/leetbook/read/illustration-of-algorithm/58pq8g/
* @param str
* @return
*/
int str_to_int(std::string str);
}; };
class ListNode { class ListNode {
@ -73,10 +82,9 @@ public:
* @return * @return
*/ */
ListNode *reverse_list(ListNode *head); ListNode *reverse_list(ListNode *head);
ListNode* reverse_list(ListNode* cur, ListNode* pre); ListNode *reverse_list(ListNode *cur, ListNode *pre);
}; };
class Node { class Node {
public: public:
int val; int val;
@ -96,7 +104,7 @@ public:
* @param head * @param head
* @return * @return
*/ */
Node* copy_random_list(Node* head); Node *copy_random_list(Node *head);
}; };
/** /**
@ -141,6 +149,5 @@ private:
* @param k * @param k
* @return * @return
*/ */
std::vector<int> max_sliding_window(std::vector<int>& nums, int k); std::vector<int> max_sliding_window(std::vector<int> &nums, int k);
} }

View File

@ -45,4 +45,22 @@ bool String::is_number(std::string s) {
return false; return false;
} }
int String::str_to_int(std::string str) {
int res = 0, bndry = INT_MAX/10;
int i = 0, sign = 1, length = str.size();
if (length == 0) return 0;
while (str[i] == ' ')
if (++i == length) return 0;
if (str[i] == '-') sign = -1;
if (str[i] == '-' || str[i] == '+') i++;
for (int j = i; j < length; j++) {
if (str[j] < '0' || str[j] > '9') break;
if (res > bndry || res == bndry && str[j] > '7')
return sign == 1 ? INT_MAX : INT_MIN;
res = res*10 + (str[j] - '0');
}
return sign*res;
}
} }

View File

@ -18,9 +18,17 @@ TEST(IsNumberTest, BasicAssertions) {
ASSERT_FALSE(s.is_number("e9")); ASSERT_FALSE(s.is_number("e9"));
} }
TEST(ReverseLeftWords, BasicAssertions) { TEST(ReverseLeftWordsTest, BasicAssertions) {
yaha::String s; yaha::String s;
ASSERT_EQ("cdefgab", s.reverse_left_words("abcdefg", 2)); ASSERT_EQ("cdefgab", s.reverse_left_words("abcdefg", 2));
ASSERT_EQ("umghlrlose", s.reverse_left_words("lrloseumgh", 6)); ASSERT_EQ("umghlrlose", s.reverse_left_words("lrloseumgh", 6));
} }
TEST(StringToIntTest, BasicAssertions) {
yaha::String s;
ASSERT_EQ(42, s.str_to_int("42"));
ASSERT_EQ(-42, s.str_to_int("-42"));
ASSERT_EQ(-42, s.str_to_int(" -42"));
ASSERT_EQ(4193, s.str_to_int("4193 with words"));
ASSERT_EQ(0, s.str_to_int("words and 987"));
}