-
Notifications
You must be signed in to change notification settings - Fork 65
/
NumberUtils.java
100 lines (93 loc) · 1.78 KB
/
NumberUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* Data-Structures-In-Java
* NumberUtils.java
*/
package com.deepak.data.structures.Utils;
/**
* Utilities for Numbers
* Note : All of these methods are for integers only,
* All others like, Double, float etc will have same implementation
*
* @author Deepak
*/
public class NumberUtils {
/**
* Method to convert string to Integer
*
* @param str
* @return {@link int}
*/
public static int toInt(final String str) {
return toInt(str, 0);
}
/**
* Method to convert string to Integer when a default value is given
*
* @param str
* @param defaultValue
* @return {@link int}
*/
public static int toInt(final String str, int defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Integer.parseInt(str);
} catch (final NumberFormatException exception) {
return defaultValue;
}
}
/**
* Method to check if string has all zeros
*
* @param str
* @return {@link boolean}
*/
public static boolean isAllZeros(final String str) {
if (str == null) {
return true;
}
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != '0') {
return false;
}
}
return str.length() > 0;
}
/**
* Find minimum out of Integer array
*
* @param array
* @return {@link int}
*/
public static int min(final int... array) {
if (array == null) {
return 0;
}
int min = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* Find maximum out of Integer array
*
* @param array
* @return {@link int}
*/
public static int max(final int... array) {
if (array == null) {
return 0;
}
int max = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
}