Larry
BAN USERBecause the value ranges are contiguous, simply use Enum to store each range as a single value. Then use Enum.values() to iterate and compare.
e.g.,
public enum Range {
B1(10001, 0.04f), B2(501, 0.05f), B3...;
int value;
float tax;
public Range(int value, float tax) {...}
public int getValue() {...}
public float getTax() {...}
}
then use
for (Range r : Range.values()) {
if (sum > r.getValue()) {
sum -= r.getValue();
tax += sum * r.getTax();
sum = r.getValue();
}
}
Good point. Updated.
public enum Roman {
M(1000), CM(900), D(500), CD(400), C(100), XC(90), L(50), XL(40), X(10), IX(9), V(5), IV(4), I(1);
int value;
public int getValue() {
return value;
}
private Roman(int value) {
this.value = value;
}
public static String toRoman(int n) {
int m;
String ret = "";
for (Roman r : Roman.values()) {
if (r.getValue() <= n) {
m = n / r.getValue();
for (int i = 0; i < m; i++) {
ret += r.toString();
}
n -= m * r.getValue();
}
}
return ret;
}
public static void main(String[] a) {
System.out.println(Roman.toRoman(1999));
}
}
enum Roman {
M(1000), D(500), C(100), L(50), X(10), V(5), I(1);
int value;
public int getValue() { return value; }
public int value(int value) { this.value = value; }
public static String toRoman(int n) {
int m;
String ret;
for (Roman r : Roman.getValues()) {
if (r.getValue() > n) {
m = n / r.getValue();
while (m-- > 0) {
ret += r.toString();
}
n -= m * r.getValue();
}
}
}
}
enum Roman {
M(1000), D(500), C(100), L(50), X(10), V(5), I(1);
int value;
public int getValue() { return value; }
public int value(int value) { this.value = value; }
public static String toRoman(int n) {
int m;
String ret;
for (Roman r : Roman.getValues()) {
if (r.getValue() < n) {
m = n / r.getValue();
while (m-- > 0) {
ret += r.toString();
}
n -= m * r.getValue();
}
}
}
}
class A {
static class Result {
int value;
Node node;
}
int sumOfTree(Node root, Result max) {
if (root == null) {
return 0;
}
int leftR = sumOfTree(root.left, max);
int rightR = sumOfTree(root.right, max);
int sum = leftR + rightR + root.value;
if (sum > max.value) {
max.value = sum;
max.node = root;
}
return sum;
}
public static void main(String[] args) {
Node root = ...; //create a tree
Result max = new Result(Integer.MIN, root);
new A().sumOfTree(root, max);
max.value; //max value
max.node; //max node
}
}
Repmarkglove17, Associate at Arista Networks
Hi, I am Mark from North Edwards, CA .I am just crazy about dance.I am not professionally trained, but ...
Repanneabush, AT&T Customer service email at Accolite software
Hello, I am Anne and I live in Tampa, USA. I am working in a company as a caretaker. I ...
1. Static class can be instantiated.
- Larry April 01, 20122. Only need handle root == null.
3. Return sum to calculate sumOfTree. Max is stored in max instance.