mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2026-01-25 07:34:05 +00:00
day 2: 69-sqrt-x
also refactored, added drivers
This commit is contained in:
12
69-sqrt-x/driver.cpp
Normal file
12
69-sqrt-x/driver.cpp
Normal 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
32
69-sqrt-x/soln.cpp
Normal 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
6
69-sqrt-x/soln.hpp
Normal file
@@ -0,0 +1,6 @@
|
||||
class Solution
|
||||
{
|
||||
public:
|
||||
int mySqrt(int x);
|
||||
bool test(int x, int answer);
|
||||
};
|
||||
Reference in New Issue
Block a user