实现数值检测

This commit is contained in:
yaha 2023-05-19 18:26:57 +08:00
parent ff08160831
commit b1260a488c
5 changed files with 49 additions and 4 deletions

View File

@ -21,6 +21,7 @@ private:
class String {
public:
std::string replace_space(std::string s);
bool is_number(std::string s);
};
class ListNode {
@ -29,6 +30,7 @@ public:
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
std::vector<int> reverse_print(ListNode *head);
void reverse_stack(ListNode *head, std::vector<int>& res);
void reverse(ListNode *head, std::vector<int>& res);
};

View File

@ -1,8 +1,8 @@
#include "jianzhi_offer.h"
namespace yaha {
void ListNode::reverse(ListNode *head, std::vector<int>& res) {
if (head==nullptr) {
void ListNode::reverse(ListNode *head, std::vector<int> &res) {
if (head == nullptr) {
return;
}
@ -10,6 +10,19 @@ void ListNode::reverse(ListNode *head, std::vector<int>& res) {
res.push_back(head->val);
}
void ListNode::reverse_stack(ListNode *head, std::vector<int> &res) {
std::stack<int> s;
while (head != nullptr) {
s.push(head->val);
head = head->next;
}
while (!s.empty()) {
res.push_back(s.top());
s.pop();
}
}
std::vector<int> ListNode::reverse_print(ListNode *head) {
std::vector<int> res;
reverse(head, res);

View File

@ -12,4 +12,14 @@ std::string String::replace_space(std::string s) {
}
return result;
}
bool String::is_number(std::string s) {
for (int i = 0; i < s.length(); ++i) {
if (s[i] >= '0' && s[i] <= '9') {
return true;
}
}
return false;
}
}

View File

@ -3,7 +3,7 @@
#include "jianzhi_offer.h"
TEST(NodeListTest, BasicAssertions) {
yaha::ListNode* node = new yaha::ListNode(1);
yaha::ListNode *node = new yaha::ListNode(1);
node->next = new yaha::ListNode(3);
node->next->next = new yaha::ListNode(2);
auto res = node->reverse_print(node);
@ -11,3 +11,14 @@ TEST(NodeListTest, BasicAssertions) {
ASSERT_EQ(3, res[1]);
ASSERT_EQ(1, res[2]);
}
TEST(NodeListStackTest, BasicAssertions) {
yaha::ListNode *node = new yaha::ListNode(1);
node->next = new yaha::ListNode(3);
node->next->next = new yaha::ListNode(2);
std::vector<int> res;
node->reverse_stack(node, res);
ASSERT_EQ(2, res[0]);
ASSERT_EQ(3, res[1]);
ASSERT_EQ(1, res[2]);
}

View File

@ -6,5 +6,14 @@ TEST(ReplaceSpaceTest, BasicAssertions) {
std::string expected = "We%20are%20happy.";
yaha::String s;
EXPECT_EQ(expected, s.replace_space(input));
ASSERT_EQ(expected, s.replace_space(input));
}
TEST(IsNumberTest, BasicAssertions) {
yaha::String s;
ASSERT_TRUE(s.is_number("0"));
ASSERT_TRUE(s.is_number(" .1 "));
ASSERT_FALSE(s.is_number("."));
ASSERT_FALSE(s.is_number("e"));
ASSERT_FALSE(s.is_number("e9"));
}