Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package crossnum;
- /**
- * Represents a number in any specified base. Instead of digits being
- * zero to base-minus-one, they can be from any specified start digit
- * to start-plus-base-minus-one.
- *
- * Supports operations for incrementing a number and summing its digits.
- *
- * @author dub_nerd
- *
- */
- public class DigitCombo {
- /**
- * Minimum value a number in the current base can have
- */
- final private int minDigit;
- /**
- * Maximum value a number in the current base can have
- */
- final private int maxDigit;
- /**
- * Overflow indicator, set if number incremented beyond its limit
- */
- private boolean overflow;
- /**
- * The digits of the number.
- */
- final private int[] digits;
- /**
- * Construct a new DigitCombo. All the digits are initially set to the
- * specified start digit.
- *
- * @param numDigits
- * the number of digits in the number to be stored.
- * @param base
- * the number base for this number.
- * @param startDigit
- * the minimum value for a digit, not necessarily zero.
- */
- public DigitCombo(int numDigits, int base, int startDigit) {
- minDigit = startDigit;
- maxDigit = startDigit + base - 1;
- digits = new int[numDigits];
- for (int i = 0; i < numDigits; i++) {
- digits[i] = 1;
- }
- }
- /**
- * Get the digits of this number.
- * @return digits
- */
- public int[] digits() {
- return digits;
- }
- /**
- * Increment the currently stored number.
- */
- public void increment() {
- // Bump the value of the least significant (i.e. last) digit.
- increment(digits.length - 1);
- }
- /**
- * Increment the value of the digit in the specified position.
- * Calls itself recursively to implement digit carry.
- * @param position the position of the digit to be incremented.
- */
- private void increment(int position) {
- if (digits[position] < maxDigit) {
- // ok -- no carry required
- digits[position]++;
- } else {
- // reset current digit to minimum, and carry over
- digits[position] = minDigit;
- if (position > 0) {
- // increment the next most significant digit
- increment(position - 1);
- } else {
- // overflow in most significant digit
- overflow = true;
- }
- }
- }
- /**
- * Get the sum of all the digits.
- * @return digit sum
- */
- public int summedDigits() {
- int total = 0;
- for (int n : digits) {
- total += n;
- }
- return total;
- }
- /**
- * Check if number has overflowed.
- * @return the overflow indicator.
- */
- public boolean isOverflow() {
- return overflow;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement