Home > Java, Programación, snippets > Fibonacci String Sum

Fibonacci String Sum

Recientemente me acabo de topar con un problema en un grupo de linkedIn que dice así:
“Sum Of letters: If Letter A=0; B=1; C=A+B; D=C+B and so on Find the sum of the letters of a given word in the input according to the above assumptions. Example: Input: MAN Output:377”

Asumiendo que el string puede contener mayúsculas y minúsculas, y debe ser tratadas por igual:


import java.lang.reflect.Field;
import java.math.BigInteger;

public class FibonacciString {
	public static void main(String[] args) {
		final String testA = "Man";
		System.out.println(getFibonacciStringSum(testA));
	}

	private static BigInteger[] getFibonacciArray(int n) {
		BigInteger[] fibonacciArray = new BigInteger[n];
		fibonacciArray[0] = BigInteger.ZERO;
		fibonacciArray[1] = BigInteger.ONE;
		for (int i = 2; i  512) {
			return traverseStringByReflection(fiboString, stringLength);
		} else {
			return traverseStringByCharAt(fiboString, stringLength);
		}
	}

	private static BigInteger traverseStringByCharAt(String fiboString,
			final int len) {
		final BigInteger[] fiboArray = getFibonacciArray(26);
		BigInteger retval = BigInteger.ZERO;
		int fiboIndex, character;
		for (int i = 0; i  96 ? character - 97 : character - 65;
			retval = retval.add(fiboArray[fiboIndex]);
		}
		return retval;
	}

	private static BigInteger traverseStringByReflection(String fiboString,
			final int len) {
		final BigInteger[] fiboArray = getFibonacciArray(26);
		BigInteger retval = BigInteger.ZERO;
		try {
			final Field valueField = String.class.getDeclaredField("value");
			valueField.setAccessible(true);
			final char[] chars = (char[]) valueField.get(fiboString);
			int fiboIndex, character;
			for (int i = 0; i  96 ? character - 97 : character - 65;
				retval = retval.add(fiboArray[fiboIndex]);
			}
		} catch (Exception e) {
			// add more exceptions
			e.printStackTrace();
		}

		return retval;
	}
}
Categories: Java, Programación, snippets
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: