Skip to content

2.add two numbers#5

Open
nicah4o wants to merge 1 commit into
mainfrom
2.add-two-numbers
Open

2.add two numbers#5
nicah4o wants to merge 1 commit into
mainfrom
2.add-two-numbers

Conversation

@nicah4o
Copy link
Copy Markdown
Owner

@nicah4o nicah4o commented May 5, 2026

}
};
```
スタックオーバーフローで上手くいかない。intは10桁、long long型で19桁。
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

整数オーバーフローでしょうか。

int ten1 = 0;
while (l1 != nullptr) {
if (l1->next == nullptr) {
n1 += l1->val;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

最後の桁はどうしてpow(10, ten1)を掛けませんか?

class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int n1, n2, n3;
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 sum, carry = 0;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

これ、sum は意図的に初期化しなかったんでしょうか。

個人的には、慣れないうちは一行に一変数にしたほうがいいと思いますね。

while (l1 || l2 || carry) {
int v1 = l1 ? l1->val : 0;
int v2 = l2 ? l2->val : 0;
sum = v1 + v2 + carry;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

sum をループ間で受け渡す必要がないので、こっちを int sum にするのも手です。

あ、これは何を言っているかというと、ループを「仕事の引き継ぎ」だと思うと、sum は引き継ぐ必要がないものと感じるということです。

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int sum, carry = 0;
ListNode dummy(-1);
ListNode* node = &dummy;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この node はどういう意味でしょうか。このループの中での役割は、主役というよりは「ここまでは確定した結果で、node->next に次の値を書き込む」という役割に見えます。主役でないならば主役でなさそうな名前をつけたほうがいいでしょう。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants