day 2: 69-sqrt-x

also refactored, added drivers
This commit is contained in:
2023-09-27 11:22:43 -07:00
parent a9d7373732
commit 9da326288a
7 changed files with 106 additions and 30 deletions

12
69-sqrt-x/driver.cpp Normal file
View File

@@ -0,0 +1,12 @@
#include "soln.hpp"
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int x = 69, answer = 8;
Solution soln;
cout << "Square root correct? " << soln.test(x, answer) << endl;
return 0;
}

32
69-sqrt-x/soln.cpp Normal file
View File

@@ -0,0 +1,32 @@
#include "soln.hpp"
#include <cmath>
int Solution::mySqrt(int x)
{
// base case
if (x == 0 || x == 1)
{
return x;
}
// effectively only till ~sqrt(x)
for (int i = 2; i <= x; i++)
{
long i_square = long(i) * i;
// x is a perfect square
if (i_square == x)
{
return int(i);
}
// x is not a perfect square
else if (i_square > x)
{
return int(i - 1);
}
}
return -1; // compiler fuss
}
bool Solution::test(int x, int answer)
{
return answer == mySqrt(x);
}

6
69-sqrt-x/soln.hpp Normal file
View File

@@ -0,0 +1,6 @@
class Solution
{
public:
int mySqrt(int x);
bool test(int x, int answer);
};