minimum number of flips to make k substring at least one 1 in binary string code example
Example 1: count number of zeros in array in O(logN)
int firstZero(int arr[], int low, int high)
{
if (high >= low)
{
int mid = low + (high - low)/2;
if (( mid == 0 || arr[mid-1] == 1) && arr[mid] == 0)
return mid;
if (arr[mid] == 1)
return firstZero(arr, (mid + 1), high);
else
return firstZero(arr, low, (mid -1));
}
return -1;
}
int countZeroes(int arr[], int n)
{
int first = firstZero(arr, 0, n-1);
if (first == -1)
return 0;
return (n - first);
}
Example 2: generate all prime number less than n java
import java.util.*;
public class Primecounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num =0;
String primeNumbers = "";
boolean isPrime = true;
System.out.print("Enter the value of n: ");
System.out.println();
int n = scanner.nextInt();
for (int i = 2; i < n; i++) {
isPrime = true;
for (int j = 2; j <= i/2; j++) {
if (i%j == 0) {
isPrime = false;
}
}
if (isPrime)
System.out.print(" " + i);
}
}
}
Example 3: Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. javascript
class Solution {
public:
vector<int> shortestToChar(string S, char C) {
int n = S.size();
vector<int> r(n, n);
for (int i = 0; i < n; ++ i) {
if (S[i] == C) r[i] = 0;
}
for (int i = 1; i < n; ++ i) {
r[i] = min(r[i], r[i - 1] + 1);
}
for (int i = n - 2; i >= 0; -- i) {
r[i] = min(r[i], r[i + 1] + 1);
}
return r;
}
};
Example 4: Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. javascript
class Solution {
public:
vector<int> shortestToChar(string S, char C) {
vector<int> r(S.size(), 0);
int prev = -S.size();
for (int i = 0; i < S.size(); ++ i) {
if (S[i] == C) prev = i;
r[i] = i - prev;
}
prev = INT_MAX;
for (int i = S.size() - 1; i >= 0; -- i) {
if (S[i] == C) prev = i;
r[i] = min(r[i], prev - i);
}
return r;
}
};