File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ package me .ramswaroop .bits ;
2
+
3
+ /**
4
+ * Created by IntelliJ IDEA.
5
+ *
6
+ * @author: ramswaroop
7
+ * @date: 6/12/15
8
+ * @time: 6:18 PM
9
+ */
10
+ public class SmallestOf3Integers {
11
+
12
+ /**
13
+ * Returns min of 2 numbers without using
14
+ * any comparison operators.
15
+ *
16
+ * @param x
17
+ * @param y
18
+ * @return
19
+ */
20
+ private static int min (int x , int y ) {
21
+ return y + ((x - y ) & ((x - y ) >> 31 ));
22
+ }
23
+
24
+ /**
25
+ * Returns the smallest element in an
26
+ * array of length 3.
27
+ *
28
+ * @param a
29
+ * @return
30
+ */
31
+ public static int getSmallest (int a []) {
32
+ return min (a [0 ], min (a [1 ], a [2 ]));
33
+ }
34
+
35
+ /**
36
+ * This method uses repeated subtraction to
37
+ * find the smallest element in an array.
38
+ *
39
+ * @param a
40
+ * @return
41
+ */
42
+ public static int getSmallest_V1 (int a []) {
43
+ int c = 0 ;
44
+ while (a [0 ] > 0 && a [1 ] > 0 && a [2 ] > 0 ) {
45
+ a [0 ]--;
46
+ a [1 ]--;
47
+ a [2 ]--;
48
+ c ++;
49
+ }
50
+ return c ;
51
+ }
52
+
53
+ public static void main (String a []) {
54
+ System .out .println (getSmallest (new int []{4 , 5 , 6 }));
55
+ System .out .println (getSmallest_V1 (new int []{4 , 5 , 6 }));
56
+ }
57
+ }
You can’t perform that action at this time.
0 commit comments