-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterview.cpp
More file actions
101 lines (86 loc) · 2.31 KB
/
Copy pathinterview.cpp
File metadata and controls
101 lines (86 loc) · 2.31 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <iostream>
#include <stdexcept>
#include <random>
int integer_division( int x, int y )
{
int result = 0;
/* return early on trivial cases */
if( x == 0 ) return 0;
if( y == 0 ) throw std::overflow_error( "Divide by zero exception" );
/* handle negative numbers appropriately */
bool negative = false;
if( x < 0 )
{
negative = !negative;
x = x - x - x;
}
if( y < 0 )
{
negative = !negative;
y = y - y - y;
}
/* do the division */
while( x - y >= 0 )
{
x -= y;
result++;
}
/* make result negative if appropriate */
if( negative )
{
result = result - result - result;
}
return result;
}
bool test_case_integer_division( int x, int y )
{
if( integer_division( x, y ) != x / y )
{
std::cout << "FAIL: integer_division( " << x << ", " << y << " ) != " << x / y << std::endl;
std::cout << "actual result: " << integer_division( x, y ) << std::endl;
return false;
}
else
{
std::cout << "PASS: integer_division( " << x << ", " << y << " ) == " << x / y << std::endl;
return true;
}
}
void test_integer_division()
{
std::random_device rd;
std::mt19937 gen( rd() );
std::uniform_int_distribution<> dis( 1, 10000 );
int tests = 20;
int failed_cases = 0;
std::cout << "--------------------" << std::endl;
std::cout << "Test case: integer_division( int x, int y )" << std::endl << std::endl;
for( int i = 0; i < tests; ++i )
{
if( !test_case_integer_division( dis( gen ), dis( gen ) ) ) ++failed_cases;
}
bool threw_exception = false;
try
{
test_case_integer_division( 5, 0 );
}
catch( std::overflow_error e )
{
std::cout << "PASS: exception thrown for divide by zero" << std::endl;
threw_exception = true;
}
if( !threw_exception ) ++failed_cases;
if( failed_cases == 0 )
{
std::cout << std::endl << "Passed all tests for integer_division( int x, int y )" << std::endl;
}
else
{
std::cout << "Failed " << failed_cases << " tests for integer_division( int x, int y )" << std::endl;
}
std::cout << "--------------------" << std::endl;
}
int main( int argv, char *argc[] )
{
test_integer_division();
}