Popads

PopAds.net - The Best Popunder Adnetwork

Hello Coders!! 

Coding practice is very necessary to all programmers. So, here we give some google interview coding problems. Improve your coding skills and try to solve it.



This Question was posted on Instagram page @_computer_engineers_ 
Follow this page to get early questions and more coding related stuff.


Question: Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers.

Test Case:  
                                Input : arr[] = { 1, 2, 4, 5, 6, 6, 8, 9} 
                                Target = 11
                                Output: 9

Note : First solve the question on your own! It will help you to build your logic.
           Solutions are in three language C++, Java, Python.

C++

//Author : _computer_engineers_

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
    int n, target, closest;
    // Input
    cout << "Enter Number of Array elements : ";
    cin >> n;
    cout << "Enter Array elements : " << endl;
    vector<int> arr;
    for(int i=0; i<n; i++)
    {
        int x;
        cin >> x;
        arr.push_back(x);
    }
    cout << "Enter Target : ";
    cin >> target;
    // Initializing closest
    closest = arr[0];
    // Finding closest
    for(int i : arr)
        if( abs(target-i) < abs(closest-target))
            closest = i;
    // Output
    cout << "\nClosest value to Target in Array : " << closest << endl;
    return 0;
}

Java

/*
Author : _computer_engineers_
*/
import java.util.Scanner;
public class Closest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, target, closest;
// Input
System.out.print("Enter Number of Array elements : ");
n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter Array elements : ");
for(int i=0; i<n; i++)
arr[i] = sc.nextInt();
System.out.print("Enter Target : ");
target = sc.nextInt();
// Initializing closest
closest = arr[0];
// Finding closest
for(int i : arr)
if( Math.abs(target-closest) > Math.abs(target-i))
closest = i;
// Output
System.out.println("Closest value to Target in Array : " + closest);
sc.close();
}
}

Python

#Author : _computer_engineers_
n = int(input("Enter Number Array elements : "))
arr = []
print("Enter Array Elements : ")
# Input of Array
for i in range(n):
    arr.append(int(input()))
# Target Input
target = int(input("Enter Target value : "))
# Initializing closest
closest = arr[0]
# Finding closest
for i in arr:
    if abs(target - i) < abs(target - closest):
        closest = i
# Output
print("\nClosest value in Array to Target : {}".format(closest))


I hope you like it, please share & subscribe for more questions and updates!

See other posts :

Comments

Like post ? Comment & Share

Previous Post Next Post