Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,037 questions

40,821 answers

573 users

How to remove characters from a numeric string such that the string becomes divisible by 8 in Java

1 Answer

0 votes
public class Program {
    public static int checkIfNumExist(String num, String s) {
        int index = 0;
        
        for (char ch : s.toCharArray()) {
            if (num.charAt(index) == ch) {
                index++;
                if (num.length() == index ) {
                    break;
                }
            }
        }
        
        return index == num.length() ? 1 : 0;
    }

    public static String convertStringToBecomesDivisibleBy8(String s) {
        for (int i = 8; i < 1e3; i += 8) {
            String num = Integer.toString(i);
            if (checkIfNumExist(num, s) == 1) {
                return num;
            }
        }
        
        return "-1";
    }

    public static void main(String[] args) {
        String s1 = "127892";
        String result = convertStringToBecomesDivisibleBy8(s1);
        System.out.println(result);
        
        String s2 = "1201674";
        result = convertStringToBecomesDivisibleBy8(s2);
        System.out.println(result);
        
        String s3 = "1209574";
        result = convertStringToBecomesDivisibleBy8(s3);
        System.out.println(result);
        
        String s4 = "190395473";
        result = convertStringToBecomesDivisibleBy8(s4);
        System.out.println(result);
        
        String s5 = "1309577";
        result = convertStringToBecomesDivisibleBy8(s5);
        if (!result.equals("-1")) {
            s5 = result;
            System.out.println(s5);
        } else {
            System.out.println("No numeric characters combination divisible by 8");
        }
    }
}



/*
run:

8
16
24
104
No numeric characters combination divisible by 8

*/

 





answered Mar 19 by avibootz
...