Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/main/cpp/leetcode/StrToInt.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/* Adding CPP implementation of the problem: https://oj.leetcode.com/problems/string-to-integer-atoi/ */

/*
*Implementing function to convert string to an integer.

*If no valid conversion could be performed, a zero value is returned.

*If the correct value is out of the range of representable values, the maximum integer value (2147483647) or the minimum integer value (–2147483648) is returned.

*For more explanation, visit- https://www.gyanblog.com/gyan/coding-interview/leetcode-string-integer-atoi/
*/

class Solution {
public:
int myAtoi(string str) {
int sign=1, i=0;
int maxdiv = INT_MAX/10;
while (str[i]==' ') i++;
if (i<str.length() && str[i]=='+') i++;
else if (i<str.length() && str[i]=='-') {
sign=-1;
i++;
}
int num=0;
while (i<str.length()) {
if (str[i]<'0' || str[i]>'9')
return sign*num;
int digit = str[i]-'0';
if (num > maxdiv || num==maxdiv && digit>=8)
return sign==1 ? INT_MAX : INT_MIN;
num = num*10 + digit;
i++;
}
return sign*num;
}
};
20 changes: 20 additions & 0 deletions src/main/cpp/leetcode/strstr.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* Adding CPP implementation of Problem : https://oj.leetcode.com/problems/implement-strstr/ */

/* Assuming n=length of haystack, m=length of needle, then -
O(nm) runtime, O(1) space complexity */

/* BRUTE FORCE: Scan the needle with the haystack from its first position and start matching all subsequent letters one by one.
If one of the letters does not match, we start over again with the next position in the haystack. */

class Solution {
public:
int strStr(string haystack, string needle) {
for (int i=0; ; i++) {
for (int j=0; ; j++) {
if (j == needle.length()) return i;
if (i+j == haystack.length()) return -1;
if (needle[j] != haystack[i+j]) break;
}
}
}
};