简体   繁体   中英

Checking numbers in a string

Notice: I know that there are tons of ways to make this simpler, but it is not allowed. I am bounded to plain, basic java, loops and hand written methods. Even arrays are not allowed.Regex as well.

Task is to check for numbers in each word of a sentence,find the word with the greatest number which is at the same time POWER OF 3. I did everything here and it works fine until I enter something like this.

asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125

I receive output 64 instead of 125, because it stops checking when it reaches first number WHICH IS NOT POWER OF 3.

How can I continue the iteration till the end of my sentence and avoid stopping when I reach non power of 3 number ,how to modify this code to achieve that ?

Edit: But if I enter more than one word after the one that FAILS THE CONDITION, it will work just fine.

for instance:

asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125 asdash216

Here is my code:

public class Nine {

static int num(String s) { // method to change string to int
    int b = 0;
    int o = 0;
    for (int i = s.length() - 1; i >= 0; i--) {
        char bi = s.charAt(i);
        b += (bi - '0') * (int) Math.pow(10, o);
        o++;

    }

    return b;
}

static boolean thirdPow(int a) {
    boolean ntrec = false;
    if (Math.cbrt(a) % 1 == 0)
        ntrec = true;
    return ntrec;

}



static int max(int a, int b) {
    int max= 0;
    if (a > b)
        max= a;
    else
        max= b;
    System.out.print(max);
    return max;
}

static String search(String r) {
    String current= ""; // 23aa64
    String currentA= "";
    String br = ""; // smjestamo nas broj iz rijeci 23
    int bb = 0; // nas pretvoreni string u broj
    int p = 0;

    for (int i = 0; i < r.length(); i++) {

        current+= r.charAt(i);
        if (r.charAt(i) == ' ') { 
            for (int j = 0; j < current.length(); j++) {
                while ((int) current.charAt(j) > 47 && (int) current.charAt(j) < 58) {
                    br += current.charAt(j); 
                    j++;
                }
                bb = num(br);
                System.out.println("Third pow" + thirdPow(bb));

                if (thirdPow(bb)) {
                    p = max(p, bb);

                }

                br = "";

            }

            current= "";

        }

    }

    String pp = "" + p;
    String finalRes= "";
    for (int u = 0; u < r.length(); u++) {
        currentA+= r.charAt(u);
        if (r.charAt(u) == ' ') {
            if (currentA.contains(pp))
                finalRes+= currentA;
            currentA= "";
        }
    }
    System.out.println(p);
    return finalRes;

}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter sentence: ");
    String r = scan.nextLine();

    System.out.println("Our string is : " + search(r));

}
  }

I am assuming that each word is separated by an empty space and containing non-Integers.

Usage of regular expressions will certainly reduce the code complexity, Let's try this code: -

String input = "asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125";

String[] extractWords = r.split(" ");        //extracting each words

int[] numbers = new int[extractWords.length]; // creating an Integer array to store numbers from each word

int i=0;

for(String s : extractWords) {
        numbers[i++] = Integer.parseInt(s.replaceAll("\\D+", "")); // extracting numbers
}

Now, the "numbers" array will contain [8, 27, 64, 333, 125]

You can use your logic to find a maximum among them. Hope this helps.

Brother use

*string.split(" ");*

to form an array of strings and then iterate through the array and parse the numbers using regex

^[0-9]

or

\d+

and then find the biggest number from the array as simple as that. Brother proceeds step by step then your code will run faster.

You can just do what I am doing. First split the sentence to chunks of words. I am doing it based on spaces, hence the in.split("\\\\s+") . Then find the numbers from these words. On these numbers check for the highest number only if it is a power of 3.

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
static boolean isPowOfThree(int num)
{
    int temp = (int)Math.pow(num, 1f/3);
    return (Math.pow(temp, 3) == num);
}

public static void main (String[] args) throws java.lang.Exception
{
    Scanner sc = new Scanner(System.in);
    String in = sc.nextLine();
    String[] words = in.split("\\s+");
    String maxWord = ""; //init default word
    int maxNum = -1; //init default num

    for(String word : words)
    {
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(word);
        while (m.find()) 
        {
          String num = m.group();
          if(isPowOfThree(Integer.parseInt(num)))
          {
            if(Integer.parseInt(num) > maxNum)
            {
                maxNum = Integer.parseInt(num);
                maxWord = word;
            }
          }
        }
    }

    if(maxNum > -1)
    {
        System.out.println("Word is : " + maxWord);
    }
    else
    {
        System.out.println("No word of power 3");
    }

}
}

The problem can be solved using \\\\d+ regular expression with Matcher and Pattern API in Java.

package com.company;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        String i = "asdas8 dasjkj278 asdjkj64 asdjk333 asdjkj125";
        Matcher matcher = Pattern.compile("\\d+").matcher(i);

        List<Integer> numbers = new ArrayList<>();
        while (matcher.find()){
            numbers.add(Integer.parseInt(matcher.group()));
        }

        Collections.sort(numbers);
        Collections.reverse(numbers);

        Integer power3 = 0;

        for (Integer n : numbers) {
            if (isPowOfThree(n)) {
                power3 = n;
                break;
            }
        }
        System.out.println(power3);
    }

    static boolean isPowOfThree(int num) {
        int temp = (int)Math.pow(num, 1f/3);
        return (Math.pow(temp, 3) == num);
    }
}

Upon using \\\\d+ regular expression we get all the digits in the given string for every iteration of while(matcher.find()) . Once we collect all the numbers in the given string, we need to reverse sort the collection. If we iterate over this collection, the first number that we find is the largest number which is a power of 3, since the collection is already sorted in descending order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM