Skip to content

Commit fb41c61

Browse files
committed
Solved 3 problems
1 parent ef3ba28 commit fb41c61

File tree

3 files changed

+91
-0
lines changed

3 files changed

+91
-0
lines changed

Easy/Count Primes.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public int countPrimes(int n) {
3+
int[] arr = new int[n];
4+
5+
for (int i=2;i<n;i++) {
6+
if (arr[i] != 1) {
7+
for (int j = i*2;j<n;j+=i) {
8+
arr[j] = 1;
9+
}
10+
}
11+
else {
12+
arr[i] = 1;
13+
}
14+
}
15+
16+
int count = 0;
17+
for (int i=2;i<n;i++) {
18+
if (arr[i] == 0) count++;
19+
}
20+
21+
return count;
22+
}
23+
}

Easy/Roman to Integer.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public int romanToInt(String s) {
3+
String symbol = "IVXLCDM";
4+
int[] val = {1, 5, 10, 50, 100, 500, 1000};
5+
6+
char[] s_char = s.toCharArray();
7+
8+
int[] s_val = new int[s_char.length];
9+
10+
for (int i=0;i<s_char.length;i++) {
11+
s_val[i] = val[symbol.indexOf(s_char[i])];
12+
}
13+
14+
int total = 0;
15+
int k = 0;
16+
17+
while (k < s_val.length) {
18+
int s1 = s_val[k];
19+
if (k+1 < s_val.length) {
20+
int s2 = s_val[k+1];
21+
22+
if (s1 >= s2) {
23+
total += s1;
24+
k++;
25+
}
26+
else{
27+
total += s2-s1;
28+
k += 2;
29+
}
30+
}
31+
else {
32+
total += s1;
33+
k++;
34+
}
35+
}
36+
37+
return total;
38+
}
39+
}

Easy/Valid Palindrome II.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public boolean validPalindrome(String s) {
3+
if (isPalindrome(s)) return true;
4+
5+
int i=0;
6+
int j = s.length()-1;
7+
8+
while (i<j && s.charAt(i) == s.charAt(j)) {
9+
i++;
10+
j--;
11+
}
12+
13+
if (i>=j) {
14+
return true;
15+
}
16+
17+
if (isPalindrome(s.substring(i+1,j+1)) || isPalindrome(s.substring(i,j))) {
18+
return true;
19+
}
20+
21+
return false;
22+
}
23+
24+
public boolean isPalindrome(String s) {
25+
StringBuilder sb = new StringBuilder("");
26+
sb.append(s);
27+
return s.equals(sb.reverse().toString());
28+
}
29+
}

0 commit comments

Comments
 (0)