Saturday, 20 April 2019

Temperatures Codingame Solution in Java

Problem:-

Write a program that prints the temperature closest to 0 among input data. If two numbers are equally close to zero, positive integer has to be considered closest to zero (for instance, if the temperatures are -5 and 5, then display 5).

 Game Input

Your program must read the data from the standard input and write the result on the standard output.
Input
Line 1: N, the number of temperatures to analyze
Line 2: A string with the N temperatures expressed as integers ranging from -273 to 5526
Output
Display 0 (zero) if no temperatures are provided. Otherwise, display the temperature closest to 0.
Constraints
0 ≤ N < 10000
Example
Input
5
1 -2 -8 4 5
Output
1

Solution:-

import java.util.*;
import java.io.*;
import java.math.*;

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/
class Solution {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt(); // the number of temperatures to analyse
        int minT=0;
        int minTN=0;
        int result=0;
        for (int i = 0; i < n; i++) {
            int t = in.nextInt(); // a temperature expressed as an integer ranging from -273 to 5526
            if(t>0)
            {
                if(minT>t||minT==0)
                {
                    minT=t;    
                }
            }
            else{
                    if(minTN<t||minTN==0)
                    {
                        minTN=t;
                    }
                }
        }
        
        if(minT>Math.abs(minTN)&&(minT>0)&&(Math.abs(minTN)>0))
        {
            result=minTN;
            
        }
        else if(minT<Math.abs(minTN)&&(minT>0)&&(Math.abs(minTN)>0))
        {
            result=minT;    
    
        }  
        else if(minT==0){
            result=minTN;
        }
        else{
            result=minT;
            }
        // Write an action using System.out.println()
        // To debug: System.err.println("Debug messages...");

        System.out.println(result);
    }
}

No comments:

Post a Comment

Error While embed the video in Your website page

Error:- Refused to display '<URL>' in a frame because it set 'X-Frame-Options' to 'sameorigin Solution:- if ...