Implement the following methods with recursion using C++: 1) //Given a string an
ID: 3784933 • Letter: I
Question
Implement the following methods with recursion using C++:
1) //Given a string and "base" value between 2 and 10, returns
//the integer represented in base "base" by string s. int baseReader(string s, int base) For example: cout << baseReader("2001", 3) << endl;
//Should print 55 cout << baseReader("31",8) << endl;
//Should print 25
3) //Assume A is a sorted array of increasing distinct integers. //return 'true' if A[i] = i for some i between start and end, 'false' if not.
//Your algorithm should run in O(log n) time, where n = end-start is the
//number of items you are considering. bool sameIndex(int * A, int start, int end) For Example:
//should return true since A[5] == 5. int A[] = {-50,-10,0,1,3,5,8,10}; cout << sameIndex(A,0,7) << endl;
//should return false. int B[] = {-50,-10,0,1,3,6,8,10}; cout << sameIndex(B,0,7) << endl;
Explanation / Answer
public class cheggexamplestring_base {
String s="";
public static void main(String[] args) {
String name="2001";
int b=3;
System.out.println(BaseReader(name,b));
}
public static int BaseReader(String s,int base){
int val=0;
for(int i=0;i<s.length();i++){
if(i==base){
val=s.charAt(i);
//System.out.println(val);
}
}
return val;
}
}
output:
49
#include <cstdlib>
#include <iostream>
using namespace std;
int binarysearch(int arr[],int start,int end, int val);
int main() {
int li[10];
for (int s=0; s<11; s++)
li[s]=2*s+1;
bool re=true;
int flag=binarysearch(li,1,21,11);
if(flag<=21)
re=true;
else
re=false;
cout<< "search boolean reslut: "<< re<<endl;
cout<< " search index: "<< flag<<endl;
return 0;
}
int binarysearch(int arr[],int start,int end, int skey)
{
int ind;
if (start > end)
ind = -1;
else
{
int midle = (start + end)/2;
if (skey == arr[midle])
ind = midle;
else
if (skey < arr[midle])
ind = binarysearch(arr,start, midle-1, skey);
else
ind= binarysearch(arr, midle+1, end, skey);
}
return ind;
}
search boolean: 1
search index: 5