Given an input string of digits, split that into groups of prime numbers by maintaining the order given in the input string and each group should hold all the characters of the input string. Find the count of such groups.
Example:
11375
Ans:
3
Explanation:
The 3 combinations are [11,37,5], [11,3,7,5] and [113,7,5]
Code that I tried
public int countPossibilities(String s) {
int n = s.length();
int[] ar = new int[n + 1];
ar[0] = 1;
for (int i = 1; i < n; i++) {
int j = i - 1;
while (j >= 0 && j >= i - 3) {
if (prime(s.substring(j, i)))
ar[i] += ar[j];
j--;
}
}
return ar[n];
}
public boolean prime(String s) {
int n = Integer.parseInt(s);
if (n < 2) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
This works fine if the input string length is small.
But the length of the input string can be from 1 to 10^5. So my program fails for large strings.
Example:
1350297079989171477791892123929141605573631151125933376097791877830238462471373933362476484818693477173990672289892448124097556197582379957168911392680312103962394732707409889862447273901522659
Expected result is : 4386816
What is the right approach to solve this problem.
Here's working Python code that answers your long example.
Let dp[i] represent the number of valid combinations ending at the ith index of the input. Then for each prime suffix of length x ending at input[i], we add to dp[i] the count of valid combinations ending at dp[i-x], provided there is also a count of valid combinations recorded for dp[i-x].
# https://rosettacode.org/wiki/Sieve_of_Eratosthenes
def primes2(limit):
if limit < 2: return []
if limit < 3: return [2]
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [False] * ((lmtbf - s) // p + 1)
return set(["2"] + [str(i + i + 3) for i, v in enumerate(buf) if v])
def f(n):
# The constant, k, limits the number
# of digits in the suffix we're
# checking for primality.
k = 6
primes = primes2(10**k)
dp = [0] * len(n) + [1]
for i in range(len(n)):
suffix = ""
for j in range(min(i + 1, k)):
suffix = n[i-j] + suffix
if suffix in primes and dp[i-j-1] > 0:
dp[i] += dp[i-j-1]
return dp[len(n) - 1]
Output:
n = "1350297079989171477791892123929141605573631151125933376097791877830238462471373933362476484818693477173990672289892448124097556197582379957168911392680312103962394732707409889862447273901522659"
print(f(n)) # 4386816
Proof of concept from my comments, but in C# (I'm an AP Comp Sci teacher that doesn't like to code in Java; go figure!):
Take the length of the input string minus 1 and call this "padLength".
Now raise 2 to the power of padLength to get the total number of
possibilities for string combinations; call this number
"numberOfCombinations". Next, count from 0 to numberOfCombinations and
convert that decimal number to a BINARY number, left padded with
zeroes out to padLength, called "binaryNumber". The binary number
represents whether or not a space should be added in-between the
digits of the original number. For instance, binary "1100" and dec
"11375" would result in "1 1 375" because 1 means put a space
in-between. This process will give you all combinations of the
original string in the different groups. Then you can extract the
numbers from the groups and see if they are primes...
Code:
private async void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length == 0) { return; }
textBox1.Enabled = false;
button1.Enabled = false;
textBox2.Clear();
String binary;
StringBuilder sb = new StringBuilder();
String input = textBox1.Text.Trim();
char[] digits = input.ToCharArray();
int padLength = input.Length - 1;
long combinations = (long)Math.Pow(2, padLength);
List<String> combos = new List<string>();
await Task.Run(() => {
for (long i = 0; i < combinations; i++)
{
binary = Convert.ToString(i, 2).ToString().PadLeft(padLength, '0');
char[] binaryDigits = binary.ToCharArray();
sb.Clear();
for (int s = 0; s < digits.Length; s++)
{
sb.Append(digits[s]);
if (s < (digits.Length - 1))
{
if (binaryDigits[s] == '1')
{
sb.Append(' ');
}
}
}
combos.Add(sb.ToString());
}
});
textBox2.Lines = combos.ToArray();
textBox1.Enabled = true;
button1.Enabled = true;
}
Output:
For very large inputs, you won't be able to compute the number of combinations using Math.Pow(), or any built-in methods for converting a decimal to a binary number. In those cases, you can "count manually" in binary by using a String directly and following the counting algorithm. You'd build the binary numbers using only String manipulation directly by inspecting each char to see if it is 1 or 0 and acting accordingly. You'll know you're done when you have a string of ones that has a length one less than the length of your input. It will run a lot slower than working with numbers directly.
Related
I am new to java and I was learning how to convert from binary to decimal and vice versa. In the case of binary to decimal, I found out that I could use parseint, but I saw other methods that didn't use it, so I tried to implement them into my code, but it didn't work for me and I got stumped.
How would I be able to use a different method for calculating binary to decimal and implement it into my code?
Here is my code:
import java.util.Scanner;
class BinaryToDecimal {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String binaryString;
char choice;
String nextLine = "Empty";
int i = 0;
choice = 'Y';
try {
do {
System.out.print("Enter a binary number: ");
binaryString = sc.nextLine();
//Find the string count
int count = binaryString.length();
for (int j = 0; j< count; j++)
{
if (binaryString.charAt(j) != '1' && binaryString.charAt(j) != '0')
{
System.out.print("Enter a binary number: ");
binaryString = sc.nextLine();
count = binaryString.length();
j=0;
}
}
i = Integer.parseInt(binaryString);
if (i>0)
System.out.println("The decimal number is: " + Integer.parseInt(binaryString, 2));
System.out.println("Continue using the calculator? Only input Y or N");
String ln = sc.next();
if(ln.length()==1){
choice = ln.charAt(0);
}
else{
choice = 'N';
}
if (sc.hasNextLine()) {
nextLine = sc.nextLine();
}
} while (choice == 'Y');
} catch (NumberFormatException nfe) {
System.out.println("Invalid input");
}
}
}
Binary math involves adding 1 and multiplying by 2. I would use a regular expression to test if the input is valid. I would use an infinite loop and break when the user gives an answer besides y when prompted to continue. Putting that together, gives a simplified
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a binary number: ");
String binaryString = sc.nextLine();
// An int value consists of up to 32 0 and 1s.
if (!binaryString.matches("[01]+") || binaryString.length() > 32) {
continue;
}
int v = 0;
for (int i = 0; i < binaryString.length(); i++) {
v *= 2;
if (binaryString.charAt(i) == '1') {
v++;
}
}
System.out.println("The decimal number is: " + v);
System.out.println("Continue using the calculator? Only input Y or N");
String ln = sc.nextLine();
if (!ln.equalsIgnoreCase("Y")) {
break;
}
}
It looks like your missing you're missing the radix which the default I use is 2. Try this and let me know what happens
i = Integer.parseInt(binaryString,2);
There may be a nicer way of doing this, however this is the solution that I came up with. I took into account that the number can both be a positive and negative number and added checks for those cases. I also made sure to add exceptions for when an invalid binary number is entered.
public static int numberFromBinary(String binaryNumber) {
char[] array = binaryNumber.toCharArray();
boolean isNegative = false;
int result = 0;
if (array.length > 32) {
throw new NumberFormatException("An integer cannot be more than 32 bits long.");
}
if (array.length == 32) {
isNegative = array[0] == '1';
if (isNegative) {
result -= 1;
}
}
for (int i = 0; i < array.length && i != 31; i++) {
int worth = (int) Math.pow(2, i);
if (array[array.length - 1] != '1' && array[array.length - 1] != '0') {
throw new NumberFormatException("Binary bits can only be a '1' or a '0'.");
}
if (isNegative) {
if (array[array.length - 1] == '0') {
result -= worth;
}
} else {
if (array[array.length - 1] == '1') {
result += worth;
}
}
}
return result;
}
Here's a solution for converting a string representation of a binary number to a decimal number, without using Integer.parseInt(). This is based on
your original question text:
How would I be able to use a different method for calculating binary to decimal and implement it into my code?
And also a comment you added:
Also i did not want to use parseint
If you take a binary number and work your way from right to left, each digit is an increasing power of 2.
0001 = 2^0 = 1
0010 = 2^1 = 2
0100 = 2^2 = 4
1000 = 2^3 = 8
You can follow this same pattern: inspect each character position of a binary string input, and raise 2 to some power to get the decimal value represented by that bit being set to 1. Here's a simple bit of code that:
prompts for user input as a binary string
starting from right and working toward the left, it checks each character, comparing against '1'
if the character is in fact 1: take note of the position, raise 2 to the next power, and add that to the running total
Here's the code:
System.out.print("enter a binary number: ");
String binaryInput = new Scanner(System.in).next();
int decimalResult = 0;
int position = 0;
for (int i = binaryInput.length() - 1; i >= 0; i--) {
if (binaryInput.charAt(i) == '1') {
decimalResult += Math.pow(2, position);
}
position++;
}
System.out.println(binaryInput + " --> " + decimalResult);
And a few sample runs:
enter a binary number: 1111
1111 --> 15
enter a binary number: 101010101
101010101 --> 341
enter a binary number: 100000000000
100000000000 --> 2048
I had an interview and I've been asked to print numbers from 1 to a 1000 digit number -
1,
2,
3,
.
.
.
.,
999999999999999999999999999999999999999999999999........
I couldn't solve it but I'm still looking for the best way to do it, because obviously, you cant use integers or floats in a case like this and because it's a job interview I couldn't use any libraries that can handle it.
Can anyone think of a good solution? preferably in Java/pseudocode.
I had an interview and I've been asked to print numbers from 1 to a 1000 digit number
I guess the kind of answer they expected you to give is:
"We need to print the numbers from 1 to 10^1000-1. Last year, $80e9 worth of processors were sold worldwide [1], even if one processor per dollar had been sold and each processor was a thousand times faster than the fastest of them all [2] and only one instruction was used to print each number and all these processors had been produced during the last 1000 years, still: 1e1000 / (80e9 - 1000 - 8.4e9 - 1000) > 1e973 seconds to print all the numbers. That is 10e956 billion years."
Anyway, if you wish wait:
BigInteger n = BigInteger.ONE;
BigInteger last = BigInteger.TEN.pow(1000);
while(n.compareTo(last) < 0) {
System.out.println(n);
n = n.add(BigInteger.ONE);
}
Assuming only System.out.print is able to use (String is a library, see [3]), a possible solution without copy over and over again strings, and with the expected output could be:
static void printDigits(int n) {
ds(0, n, new byte[n]);
}
static void ds(int p, int k, byte[] d) {
if (p < d.length) { // if more digits to print
for (byte i = 0; i < 10; i++) { // from digit 0 to 9
d[p] = i; // set at this position
ds(p + 1, i == 0 ? k : (p < k ? p : k), d); // populate next storing first non-zero
}
} else {
if(k < d.length) { // if is not zero
if(k < d.length - 1 || d[d.length - 1] != 1) // if is not one
System.out.print(", "); // print separator
for(int i = k; i < d.length; i++) // for each digit
System.out.print((char)('0' + d[i])); // print
}
}
}
then, for printDigits(5) the output is
1, 2, 3, 4, ..., 99999
[1] https://epsnews.com/2020/09/14/total-microprocessor-sales-to-edge-slightly-higher-in-2020/
[2] https://en.wikipedia.org/wiki/Clock_rate
[3] https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Using recursion (if only to print):
void digits(int count) {
if (count < 0) throw new IllegalArgumentException("invalid count: " + count);
digits(count, "");
}
void digits(int count, String text) {
if (count == 0) {
System.out.println(text);
} else {
for (var i = 0; i < 10; i++) {
if (i == 0 && text.isEmpty()) {
digits(count-1, text);
} else {
digits(count-1, text+i);
}
}
}
}
This question already has answers here:
How do I find the sum of all odd digits of user input numeric string?
(5 answers)
Closed 2 years ago.
How to compute the sum of all 'odd digits of an input' using 'loop'. (For example, if the input is 32677, the sum would be 3 + 7 + 7 = 17.)
I can't quite figure out how to do that, can someone please help me out. This is what I have done so far, I don't know how to complete it or whether I have its right or wrong.
Any help would be appreciated!
System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();
int sum = 0;
int digits = 0;
for (int i = 0; i < length; i++) {
if (length % 2 == 1) {
digits += i;
sum = digits++;
}
}
System.out.println(sum);
Here comes a Java8-based solution:
final int result = input.chars()//make a stream of chars from string
.mapToObj(String::valueOf) // make every character a String to be able to use parseInt later
.mapToInt(Integer::parseInt) // transform character in int
.filter(i -> i % 2 == 1) // filter out even numbers
.sum();
You don't need to use String if your input is not so long.
also for safe side use long datatype.
Here is the working code with comments (explain each step).
long sumOddDigits(long value){
long temp = value; // copy in temp variable
long sum = 0;
while(temp > 0){
int digit = temp%10; // get last digit of number. example: 227 gives 7.
temp = temp / 10; // remove that last digit from number.227 will be 22.
if(digit % 2 == 1){
sum += digit;
}
}
return sum;
}
Your interpretation of the digits inside of input is not working this way.
System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();
int sum = 0;
for (int i = 0; i < length; i++) {
int digit = input.charAt(i) - '0';
if (digit % 2 == 1) {
System.out.println("Add digit: " + digit);
sum += digit;
}
}
System.out.println(sum);
In your loop, use Integer.parseInt(input.charAt(i)) to get the number at position i.
if(length%2==1){ that doesn't make sense here. You want to check if your number is odd, not the length of your string.
Given an integer N, i am trying to find the nth binary palindrome.I have written the following code but it is not efficient.is there a more efficient way in terms of time complexity.
I was trying it out as a problem online and i was supposed to output in 1 sec or less but for every input it takes 2 seconds.
public static Boolean Palind(String n){
String reverse = "";
int length = n.length();
for(int i = length - 1; i >=0;i--){
reverse = reverse + n.charAt(i);
}
if(n.equals(reverse)){
return true;
}
else{
return false;
}
}
public static int Magical(int n){
ArrayList<Integer> res = new ArrayList<Integer>();
for(int i = 1; i < Math.pow(2, n);i++){
if(Palind(Integer.toBinaryString(i))){
res.add(i);
}
}
return res.get(n-1);
}
The relevant OEIS entry (A006995) has a lot of nice tips if you read through it. For example, a(2^n-1)=2^(2n-2)-1 lets you skip right to the (2n - 1)th palindrome really quickly.
It also gives several implementations. For example, the Smalltalk implementation works like this (note that the input value, n, starts with 1 for the first palindrome, 0):
public static final int nthBooleanPalindrome(int n) {
if (n == 1) return 0;
if (n == 2) return 1;
int m = 31 - Integer.numberOfLeadingZeros(n);
int c = 1 << (m - 1);
int b;
if (n >= 3*c) {
int a = n - 3*c;
int d = 2*c*c;
b = d + 1;
int k2 = 1;
for (int i = 1; i < m; i++) {
k2 <<= 1;
b += a*k2/c%2*(k2 + d/k2);
}
}
else {
int a = n - 2*c;
int d = c*c;
b = d + 1 + (n%2*c);
int k2 = 1;
for (int i = 1; i < m - 1; i++) {
k2 <<= 1;
b += a*k2/c%2*(k2 + d/k2);
}
}
return b;
}
Try something like this maybe?
public static void main(String[] args) {
for (int i = 1; i < 65535; i++) {
System.out.println(
i + ": " + getBinaryPalindrom(i) + " = " + Integer.toBinaryString(getBinaryPalindrom(i)));
}
}
public static int getBinaryPalindrom(int N) {
if (N < 4) {
switch (N) {
case 1:
return 0;
case 2:
return 1;
case 3:
return 3;
}
throw new IndexOutOfBoundsException("You need to supply N >= 1");
}
// second highest to keep the right length (highest is always 1)
final int bitAfterHighest = (N >>> (Integer.SIZE - Integer.numberOfLeadingZeros(N) - 2)) & 1;
// now remove the second highest bit to get the left half of our palindrom
final int leftHalf = (((N >>> (Integer.SIZE - Integer.numberOfLeadingZeros(N) - 1)) & 1) << (Integer.SIZE -
Integer.numberOfLeadingZeros(N) - 2)) | ((N << (Integer.numberOfLeadingZeros(N) + 2)) >>> (Integer.numberOfLeadingZeros(N) + 2));
// right half is just the left reversed
final int rightHalf = Integer.reverse(leftHalf);
if (Integer.numberOfLeadingZeros(leftHalf) < Integer.SIZE / 2) {
throw new IndexOutOfBoundsException("To big to fit N=" + N + " into an int");
}
if (bitAfterHighest == 0) {
// First uneven-length palindromes
return (leftHalf << (Integer.SIZE - Integer.numberOfLeadingZeros(leftHalf)) - 1) | (rightHalf
>>> Integer.numberOfTrailingZeros(rightHalf));
} else {
// Then even-length palindromes
return (leftHalf << (Integer.SIZE - Integer.numberOfLeadingZeros(leftHalf))) | (rightHalf
>>> Integer.numberOfTrailingZeros(rightHalf));
}
}
The idea is that each number will become a palindrome once it reverse is added. To have the halves correctly aligned the halves just need to be shifted in place.
The problem why this has gotten a bit complex is that all uneven-length palindromes of a given leftHalf length come before all even-length palindromes of a given leftHalf length. Feel free to provide a better solution.
As int has 32 bit in Java there is a limit on N.
int-Version on ideone.com
And a BigInteger-version to support big values. It is not as fast as the int-version as the byte[]-arrays which store the value of the BigInteger create some overhead.
public static void main(String[] args) {
for (BigInteger i = BigInteger.valueOf(12345678); i.compareTo(BigInteger.valueOf(12345778)) < 0; i = i
.add(BigInteger
.ONE)) {
final BigInteger curr = getBinaryPalindrom(i);
System.out.println(i + ": " + curr + " = " + curr.toString(2));
}
}
public static BigInteger getBinaryPalindrom(BigInteger n) {
if (n.compareTo(BigInteger.ZERO) <= 0) {
throw new IndexOutOfBoundsException("You need to supply N >= 1");
} else if (n.equals(BigInteger.valueOf(1))) {
return BigInteger.valueOf(0);
} else if (n.equals(BigInteger.valueOf(2))) {
return BigInteger.valueOf(1);
} else if (n.equals(BigInteger.valueOf(3))) {
return BigInteger.valueOf(3);
}
final int bitLength = n.bitLength() - 1;
// second highest to keep the right length (highest is always 1)
final boolean bitAfterHighest = n.testBit(bitLength - 1);
// now remove the second highest bit to get the left half of our palindrom
final BigInteger leftHalf = n.clearBit(bitLength).setBit(bitLength - 1);
// right half is just the left reversed
final BigInteger rightHalf;
{
byte[] inArray = leftHalf.toByteArray();
byte[] outArray = new byte[inArray.length];
final int shiftOffset = Integer.SIZE - Byte.SIZE;
for (int i = 0; i < inArray.length; i++) {
outArray[inArray.length - 1 - i] = (byte) (Integer.reverse(inArray[i]) >>> shiftOffset);
}
rightHalf = new BigInteger(1, outArray).shiftRight(outArray.length * Byte.SIZE - bitLength);
}
if (!bitAfterHighest) {
// First uneven-length palindromes
return leftHalf.shiftLeft(bitLength - 1).or(rightHalf);
} else {
// Then even-length palindromes
return leftHalf.shiftLeft(bitLength).or(rightHalf);
}
}
I have the same idea with #Kiran Kumar: you should not count number one by one to find if it is a binary palindrome which is too slow, but rather find the internal pattern that number has.
List the number in binary string one by one, you can find the pattern:
0
1
11
101
1001
1111
...
1......1
And the following is some math problem:
We have 2^round_up((L-2)/2) palindrome of number with length L in binary format.
Sum up every shorter length number, we get following len to sum mapping:
for (int i = 1; i < mapping.length; i++) {
mapping[i] = (long) (mapping[i - 1] + Math.pow(2, Math.ceil((i - 1) * 1.0 / 2)));
}
If we find N range in [count(L), count(L+1)), we can concat it with remaining number:
public static long magical(long n) {
if (n == 0 || n == 1) {
return n;
}
long N = n - 2;
return Long.parseLong(concat(N), 2);
}
private static String concat(long N) {
int midLen = Arrays.binarySearch(indexRange, N);
if (midLen < 0) {
midLen = -midLen - 1;
}
long remaining = N - indexRange[midLen];
String mid = mirror(remaining, midLen);
return '1' + mid + '1';
}
private static String mirror(long n, int midLen) {
int halfLen = (int) Math.ceil(midLen * 1.0 / 2);
// produce fixed length binary string
final String half = Long.toBinaryString(n | (1 << halfLen)).substring(1);
if (midLen % 2 == 0) {
return half + new StringBuilder(half).reverse().toString();
} else {
return half + new StringBuilder(half).reverse().toString().substring(1);
}
}
Full code with test for produce large possible long can be found in my git repo.
Idea to optimize,
Let's look at the palindrome sequence 0, 1, 11, 101, 111, 1001 etc...
All numbers must begin and end with 1, So the middle bits only changes and midle substring should be palindrome for full string to become palindrome,
So let's take a 2 digit binary number - one palindrome is possible.
The binary of the decimal 3 is a palindrome. 11
For a 3 digit binary number 2 palindromes are possible, 2*(no of 1 digit palindrome)
The binary of the decimal 5 is a palindrome. 101
The binary of the decimal 7 is a palindrome. 111
For 5 digit binary number 4 palindromes are possible 2*(no of 3 digit palindrome)
10001,10101, 11011, 11111
and so on,
So it will be 2 + 20 + 21 + 22 +...... +2i-N ,
we solve for i and find out the palindrome number.
So by analysing this sequence we get an equation like 2(i/2)+1 -1 = N
where N is the No of palindrome,
and i is the number of bits in the nth palindrome string,
using this we can find the length of the String, from this we can find the string early.
This might be complex, but helps in solving higher values of N quickly....
CUSIPs are a 9-digit alphanumeric code for uniquely identifying a financial security.
https://en.wikipedia.org/wiki/CUSIP
They were invented in the 1964, and given the reliability of data transmission in the 60's, the 9th digit is actually a check digit used to confirm the validity of the first 8 characters. Sometimes, even today, you might find reason to want to validate a CUSIP, or perhaps a company or service obnoxiously decides to only transmit the 8-character CUSIP, even though this defeats the purpose of a check digit.
The procedure to generate the check digit is:
Convert non-numeric digits to values according to their ordinal position in the alphabet plus 9 (A=10, B=11,...Z=35) and converting the characters *=36, #=37, #=38.
Multiply every even digit by 2
If the result of the multiplication is a two-digit number, add the digits together. (12 = 1 + 2 = 3)
Get the sum of all values.
Get the floored value of this operation: (10 - (sum modulo 10)) modulo 10.
What is the best/simplest way to get this value in C#?
public string GenerateCheckDigit(string cusip)
{
int sum = 0;
char[] digits = cusip.ToUpper().ToCharArray();
string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ*##";
for (int i = 0; i < digits.Length; i++)
{
int val;
if (!int.TryParse(digits[i].ToString(), out val))
val = alphabet.IndexOf(digits[i]) + 10;
if ((i % 2) != 0)
val *= 2;
val = (val % 10) + (val / 10);
sum += val;
}
int check = (10 - (sum % 10)) % 10;
return check.ToString();
}
Edit:
.NET Fiddle demonstrating this: https://dotnetfiddle.net/kspQWl
If you pre-compute the values of check digits, and store them in a lookup table, your computation of check digit would become much simpler:
private static readonly int[,] Check = new int[128, 2];
static CusipCheckSum() {
var cusipChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*##";
for (var i = 0 ; i != cusipChars.Length ; i++) {
Check[cusipChars[i], 0] = i%10 + i/10;
Check[cusipChars[i], 1] = 2*i%10 + 2*i/10;
}
}
With the 2D lookup array in place you can compute check digit in a single line of code:
var checkDigit = (10-(cusip.Select((ch, pos) => Check[ch, pos%2]).Sum()%10))%10;
I see that there is no algo for java so adding it as well:
String generateCusipCheckDigit(String cusip) {
final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ*##";
int sum = 0;
int value = 0;
char[] cusipChars = cusip.toUpperCase().toCharArray();
for (int i = 0; i < cusipChars.length; i++) {
char actualChar = cusipChars[i];
if (Character.isDigit(actualChar)) {
value = Integer.parseInt(String.valueOf(actualChar));
} else if (Character.isAlphabetic(actualChar)){
value = alphabet.indexOf(actualChar) + 10;
} else if (cusipChars[i] == '*'){
value = 36;
} else if (cusipChars[i] == '#'){
value = 37;
} else if (cusipChars[i] == '#'){
value = 38;
}
if ((i % 2) != 0){
value *= 2;
}
value = (value % 10) + (value / 10);
sum += value;
}
int check = (10 - (sum % 10)) % 10;
return String.valueOf(check);
}
and some tests:
#Test
void checkDigitTest1(){
String actual = generator.generateCusipCheckDigit("925524BF");
Assertions.assertEquals("6", actual);
}
#Test
void checkDigitTest2(){
String actual = generator.generateCusipCheckDigit("90284B96");
Assertions.assertEquals("2", actual);
}
#Test
void checkDigitTest3(){
String actual = generator.generateCusipCheckDigit("90284B97");
Assertions.assertEquals("0", actual);
}