-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreversebinary.cpp
67 lines (54 loc) · 1.17 KB
/
reversebinary.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
58
59
60
61
62
63
64
65
66
67
/**
* @file reversebinary.cpp
* @author William Weston
* @brief Reversed Binary Numbers Problem by Kattis
* @version 0.1
* @date 2023-06-17
*
* @copyright Copyright (c) 2023
*
* Source: https://open.kattis.com/problems/reversebinary
*/
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <string>
#include <string_view>
auto reverse_binary( int N ) -> std::string;
auto from_binary( std::string_view binary ) -> int;
auto
main() -> int
{
int N;
while ( std::cin >> N )
{
std::cout << from_binary( reverse_binary( N ) ) << '\n';
}
return EXIT_SUCCESS;
}
auto
reverse_binary( int N ) -> std::string
{
auto result = std::string();
while ( N > 0 )
{
auto const remainer = N % 2;
auto const binary_char = '0' + remainer;
result += binary_char;
N /= 2;
}
return result;
}
auto
from_binary( std::string_view binary ) -> int
{
auto place = 0;
auto result = 0;
for ( auto rfirst = binary.rbegin(), rlast = binary.rend(); rfirst != rlast; ++rfirst )
{
if ( *rfirst == '1' )
result += std::pow( 2, place );
++place;
}
return result;
}