-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd1.cpp
More file actions
59 lines (47 loc) · 868 Bytes
/
add1.cpp
File metadata and controls
59 lines (47 loc) · 868 Bytes
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
58
//
// Copyright (c) 2019 David Davis. All rights reserved.
//
// Compiled on macOS with:
//
// clang++ -O2 -std=c++14 -o add1 add1.cpp
//
static const char copyright[] __attribute((used)) =
"Copyright (c) 2019 David Davis. All rights reserved.";
#include <iostream>
#include <string>
#include <stdexcept>
void usage(const char* programName)
{
std::cout << "usage: " << programName << " base_10_number\n";
}
int add1(int val)
{
int carry;
int result;
result = val ^ 1;
carry = val & 1;
while (carry)
{
result ^= (carry << 1);
carry = val & (carry << 1);
}
return result;
}
int main(int argc, const char** argv)
{
if (--argc == 1)
{
try
{
int val = std::stoi(std::string(argv[1]));
std::cout << "result: " << add1(val) << std::endl;
}
catch (std::exception)
{
usage(argv[0]);
}
}
else
usage(argv[0]);
return 0;
}