Math
Q1: Pow(x, n)
class Solution {
public:
double myPow(double x, long int n) {
long int N;
if (n < 0) {
N = -(long)n;
return 1.0 / sol(x, N);
}
return sol(x, n);
}
double sol(double x, long int n) {
if(n == 0) return 1;
else if(n == 1) return x;
else if(n%4 == 0) {
double y = sol(x, n/4);
return y*y*y*y;
}
else if(n%2 == 0) {
double y = sol(x, n/2);
return y*y;
}
else {
double y = sol(x, (n-1)/2);
return y*y*x;
}
}
};
Q2: Multiply Strings
class Solution {
public:
string multiply(string num1, string num2) {
if(num1[0] == '0' || num2[0] == '0') return "0";
string sum(num1.size() + num2.size(), '0');
for (int i = num1.size() - 1; i >= 0; i--) {
int carry = 0;
for (int j = num2.size() - 1; j >= 0; j--) {
int temp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
sum[i + j + 1] = temp % 10 + '0';
carry = temp / 10;
}
sum[i] += carry;
}
int i = 0;
while(sum[i] == '0') i++; // removing prefix zeroes
string res = "";
for(i; i < sum.size(); i++) res += sum[i];
return res;
}
};
Last updated
Was this helpful?