Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions 01-15/2.Add-Two-Numbers/6.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#if __has_include("../../debug.hpp")
#include "../../debug.hpp"
#endif
// ここまでローカルでのデバッグ用なので気にしないでください --------------------

using namespace std;

struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};

// <時間>
// 5分
// <感想>
// 久しぶりに書き直したら5.cppとほぼ同じものが出来上がった。
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

シンプルにまとまっていて読みやすかったです

// <コメント>
// - 特になし。
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry = 0;
ListNode sentinel, *node = &sentinel;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

同一の行で値型やポインター型等の型を混ぜて宣言すると、読みづらく感じます。分けて書いたほうがよいと思います。

https://google.github.io/styleguide/cppguide.html#Pointer_and_Reference_Expressions

It is allowed (if unusual) to declare multiple variables in the same declaration, but it is disallowed if any of those have pointer or reference decorations. Such declarations are easily misread.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

なるほどです!ありがとうございます!

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

私は2行にしますね。

while (l1 || l2 || carry) {
int sum = carry;
if (l1) {
sum += l1->val;
l1 = l1->next;
}
if (l2) {
sum += l2->val;
l2 = l2->next;
}
node = node->next = new ListNode(sum % 10);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

この記法知りませんでしたが,とても便利ですね.参考になります.

carry = sum / 10;
}
return sentinel.next;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

以前解かれていた 5.cpp のファイルには空行がいくつかありましたが、それらをなくしたこちらのコードの方が読みやすく感じました。

};