Quantcast
Channel: User user2023861 - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 35

Answer by user2023861 for Given two int values, return the one closer to 10

$
0
0

A little math can shorten this. Take the average of the two numbers. If the average is higher than 10, that means the higher number is pulling up the average more than the lower number is pulling it down. So return the lower number. If lower, then return higher. If 10, return 0.

public static int Closer(int a, int b){    double avg = ((double)a + (double)b) / 2.0;    return (a == b || avg == 10.0) ? 0 :           avg > 10.0 ? Math.Min(a,b) : Math.Max(a,b);}

This may not be the best solution because it's not immediately clear what this code is doing.

Edit: Made a small change in the case that a == b is true. I now treat that the same as how I treat two numbers equidistant from 10: I return 0. Thanks Lyle's Mug


Viewing all articles
Browse latest Browse all 35

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>