-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_two_numbers.cpp
57 lines (44 loc) · 1.46 KB
/
add_two_numbers.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Copyright (c) Omar Boukli-Hacene. All rights reserved.
// Distributed under an MIT-style license that can be
// found in the LICENSE file.
// SPDX-License-Identifier: MIT
#include "forfun/add_two_numbers.hpp"
#include <cassert>
#include <forward_list>
namespace forfun::add_two_numbers::stl {
[[nodiscard]] auto add_two_numbers(
std::forward_list<unsigned int> const& addend_a,
std::forward_list<unsigned int> const& addend_b
) noexcept -> std::forward_list<unsigned int>
{
auto addend_a_iter{addend_a.cbegin()};
auto const addend_a_end{addend_a.cend()};
auto addend_b_iter{addend_b.cbegin()};
auto const addend_b_end{addend_b.cend()};
std::forward_list<unsigned int> result{};
auto back_iter{result.before_begin()};
unsigned int carry{0U};
unsigned int column_sum{0U};
while ((addend_a_iter != addend_a_end) || (addend_b_iter != addend_b_end))
{
if (addend_a_iter != addend_a_end)
{
assert(*addend_a_iter <= 9U);
column_sum += *addend_a_iter++;
}
if (addend_b_iter != addend_b_end)
{
assert(*addend_b_iter <= 9U);
column_sum += *addend_b_iter++;
}
back_iter = result.insert_after(back_iter, column_sum % 10U);
carry = column_sum / 10U;
column_sum = carry;
}
if (carry != 0U)
{
result.insert_after(back_iter, carry);
}
return result;
}
} // namespace forfun::add_two_numbers::stl