-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_two_numbers.cpp
More file actions
53 lines (41 loc) · 1.33 KB
/
add_two_numbers.cpp
File metadata and controls
53 lines (41 loc) · 1.33 KB
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
// 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
) -> std::forward_list<unsigned int>
{
std::forward_list<unsigned int> result{};
auto back_iter{result.before_begin()};
auto iter_a{addend_a.cbegin()};
auto iter_b{addend_b.cbegin()};
unsigned int column_sum{};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-do-while)
do
{
if (iter_a != addend_a.cend()) [[likely]]
{
assert(*iter_a <= 9U);
column_sum += *iter_a++;
}
if (iter_b != addend_b.cend()) [[likely]]
{
assert(*iter_b <= 9U);
column_sum += *iter_b++;
}
back_iter = result.emplace_after(back_iter, column_sum % 10U);
column_sum /= 10U;
} while ((iter_a != addend_a.cend()) || (iter_b != addend_b.cend()));
if (column_sum != 0U)
{
result.insert_after(back_iter, column_sum);
}
return result;
}
} // namespace forfun::add_two_numbers::stl