Problem: I am playing around in Java and I am trying to count consecutive 'characters' within a string.
Example:
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String binaryString = Integer.toBinaryString(n);
The above code returns a binary string of the integer value entered. If we input the number 5 this will return: 101
I now wish to loop through the String and check if there are any consecutive 1's within the String.
for (int i = 0; i < binaryString.lenth(); i++)
{
// code comes here...
}
I am not sure how I can check this. I have tried the following:
for (int i = 0; i < binaryString.length(); i++)
{
char charAtPos = binaryString.charAt(i);
char charAtNextPos = binaryString.charAt(i+1);
if (charAtPos == '1')
{
if (charAtPos == charAtNextPos)
{
consecutive += 1;
}
}
}
But this obviously throws an ArrayIndexOutOfBounds as i+1 will produce a number larger than the array length.
Thank you in advance for your answers.
Owen
try running the for loop for size one less than the length of the strin
for (int i = 0; i < (binaryString.length()-1); i++)
{
char charAtPos = binaryString.charAt(i);
char charAtNextPos = binaryString.charAt(i+1);
if (charAtPos == '1')
{
if (charAtPos == charAtNextPos)
{
consecutive += 1;
}
}
}
You only need 1 line:
binaryString.split("1(?=1)").length() - 1;
We can still simplify your code using and operator
import java.util.Scanner;
class StackBinary
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String n = Integer.toBinaryString(in.nextInt());
for (int i = 0; i < n.length()-1; i++)
{
char charAtPos = n.charAt(i);
char charAtNextPos = .charAt(i+1);
if (charAtPos == '1' && charAtNextPos == '1')
{
consecutive+=1;
}
}
}
Related
The input is supposed to have an even length. The problem is that on the first iteration of the loop, it print Sc, but then it prints ch instead of ho. I'm not sure how to make that jump.
public static void twoAtATime(String a) { // School
int len = a.length();
if(len%2 == 0) {
for(int i = 0; i <a.length()/2; i++) {
System.out.print(a.substring(i,i+1) + a.substring(i+1,i+2));
System.out.println();
}
}
The output is supposed to be like this:
Sc
ho
ol
To fix it:
Increase i by 2.
Iterate until i < len.
You can improve it:
By calling substring once for two chars.
Using println with param.
Incrementing i once - i += 2.
After improvements:
public static void twoAtATime(String s) {
int len = s.length();
if (len % 2 == 0) {
for (int i = 0; i < len; ) {
System.out.println(s.substring(i, i += 2));
}
}
}
Example:
If i give a number 12345 , i should get an answer like 15243
in the same way if it is 123456 , i should get 162534
i have already tried getting the first value and appending the last value using reverse technique
public class MyFirstJavaProgram {
public static void main(String []args) {
String str = "12345";
String val = str;
char a;
int num=0;
int d=0;
int n;
for(int i=0; i<=str.length()/2; i++) {
a = str.charAt(i);
num = num*10+Character.getNumericValue(a);
if(Integer.parseInt(str)!=0){
d=Integer.parseInt(str)%10;
num = num*10+d;
n=Integer.parseInt(str)/10;
str = Integer.toString(n);
}
}
System.out.println(num);
}
}
i should get the result if they give even number or odd number
Without doing what is presumably homework for you, imagine you have a loop in which there are two integer variables a and b. Variables a and b are string indexes.
You are taking characters from the string at positions a,b,a,b,a,b etc.
BUT the values of a and b need to change for each iteration. If the length of the String is n, a will follow the sequence 0,1,2,3... and b will follow the sequence (n-1),(n-2),(n-3) etc
The loop should continue while a < b.
This is my solution for your exercise:
Method parameter "A" is Integer number you want to parse.
First you create Char Array from given number and then iterate through it. If i%2 == 0 it means that you take number from beginning otherwise from the end
public static int algorithm(int A) {
StringBuilder shuffleNumber = new StringBuilder();
char[] numbersArray = Integer.toString(A).toCharArray();
for (int i = 0; i < numbersArray.length; i++) {
if (i % 2 == 0)
shuffleNumber.append(numbersArray[i / 2]);
else
shuffleNumber.append(numbersArray[numbersArray.length - i / 2 - 1]);
}
return Integer.parseInt(shuffleNumber.toString());
}
If you want a solution without string methods, there is a not so complicated one:
public static void main(String[] args) throws IOException {
String str = "1234567";
int len = str.length();
int num=0;
char a;
for(int i = 0; i < len / 2; i++) {
a = str.charAt(i);
num = num * 10 + Character.getNumericValue(a);
a = str.charAt(len -1 - i);
num = num * 10 + Character.getNumericValue(a);
}
if (len % 2 == 1) {
a = str.charAt(str.length() / 2);
num = num * 10 + Character.getNumericValue(a);
}
System.out.println(num);
}
will print
1726354
Check the last if that takes care the case of odd number of digits in the number.
public class MyFirstJavaProgram {
public static void main(String []args) {
String str = "12345678";
int val = str.length();
char a;
int num=0;
int d=0;
int n;
for(int i=0; i<=str.length()-2; i++)
{
a = str.charAt(i);
num = num*10+Character.getNumericValue(a);
if(Integer.parseInt(str)!=0)
{
d=Integer.parseInt(str)%10;
num = num*10+d;
n=Integer.parseInt(str)/10;
str = Integer.toString( n );
}
}
if(val%2!=0)
{
num = num*10+Integer.parseInt(str)%10;
System.out.println(num);
}
else{System.out.println(num);}
}
}
this is working for my question... Thanks all
Following is my solution -
public static void solution(String s) {
StringBuffer st = new StringBuffer();
for (int i = 0; i < s.length() / 2; i++) {
st.append(s.charAt(i));
st.append(s.charAt(s.length() - 1 - i)); // appending characters from last
}
if (s.length() % 2 != 0) {
st.append(s.charAt(s.length() / 2));
}
System.out.println(Integer.parseInt(st.toString()));
}
my logic is to keep appending first and last character to new string till i < s.length/2.
If string is of odd length , it means only last character is remaining, append it to your resultant string.
Else , no character is left and you have your complete string.
I was trying to solve the Maximum Integer Value problem form Geeksforgeeks.
The problem states the following:
Given a string S of digits(0-9), your task is to find the maximum value that can be obtained from the string by putting either '*' or '+' operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input denoting the string.
Output:
For each testcase, print the maximum value obtained.
this is what I did:
class GFG
{
public static void sort(int[] numbers)
{
int n = numbers.length;
for (int i = 1; i < n; ++i)
{
int key = numbers[i];
int j = i - 1;
while (j >= 0 && numbers[j] > key)
{
numbers[j + 1] = numbers[j];
j = j -1 ;
}
numbers[j + 1] = key;
}
System.out.println(numbers.length - 1);
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
int [] maxNum;
for(int i = 0; i< testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
maxNum = new int [cNumbers.length];
for(int j = 0; j + 1 < cNumbers.length; j++)
{
int sum = 0;
int mult = 0;
sum = cNumbers[j] + cNumbers[j + 1];
mult = cNumbers[j] * cNumbers[j + 1];
int maxNumber = Math.max(sum, mult);
maxNum[i] = maxNumber;
}
sort(maxNum);
}
}
}
an example of Input:
2
01230
891
My Output:
-1
4
Correct Output:
9
73
What is wrong with my code?!
Just quick glance it would seem if your digit is less than two it should be added. 2 or larger should get multiplied. Not at a PC to test though.
The idea is to put the operators alternatively and choose the maximum results.
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.parseInt(sc.nextLine());
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
int max = 0;
for (int j = 0; j + 1 < numbers.length(); j++) {
int next = Integer.parseInt(numbers.substring(j, j+1));
if (max + next > max * next)
max = max + next;
else
max = max * next;
}
System.out.println(max);
}
sc.close();
}
}
After the execution of
int testCases = sc.nextInt();
the buffer contains a new line character. So when executing the line
String numbers = sc.nextLine();
it read '\n' into numbers, so you got -1 as the first output.
Also you need to convert character to Integer before using it any arithmetic operations.
sum = cNumbers[j] + cNumbers[j+1];
mult = cNumbers[j] * cNumbers[j+1];
So the above code will give you wrong results.
I tried the following sample and worked.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputAsString = sc.nextLine();
int testCases = Integer.parseInt(inputAsString);
int maxNumber = 0;
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
if(!numbers.matches("\\d+")){
System.out.println("Only numeric values are expected.");
continue;
}
char[] cNumbers = numbers.toCharArray();
int sum = 0;
int mult = 1;
for (int j = 0; j < cNumbers.length; j++) {
int nextNumber = Character.getNumericValue(cNumbers[j]);
sum = sum + nextNumber;
mult = mult * nextNumber;
maxNumber = mult > sum ? mult : sum;
sum = maxNumber;
mult = maxNumber;
}
System.out.println(maxNumber);
}
sc.close();
}
I read your description and what you do is wrong. please read question carefully specially the example in reference site.
as mentioned in comments by moilejter you use sc.nextInt() which doesn't read '\n' and make problem. the next sc.nextLine() will read only a empty string and your program throw exception.
Second problem is that you must calculate max continuously and you don't need an int array (you calculate max result of operation between two successive number and save them in an array which is not correspond to max integer value. you only find max between each two digit but not max of operation on all digit).
Third problem is that you use character as numbers which is made incorrect result. (you must convert them to integer)
So there is a code that works for your output:
public class GFG
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.valueOf(sc.nextLine());
for (int i = 0; i < testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
long maxUntilNow = cNumbers[0] - '0';
for (int j = 1; j < cNumbers.length; j++)
{
int numberOfThisPlace = cNumbers[j] - '0';
maxUntilNow = Math.max(maxUntilNow + numberOfThisPlace,
maxUntilNow * numberOfThisPlace);
}
System.out.println(maxUntilNow);
}
}
}
I hope this is what you want.
As per the problem statement, we need to obtain maximum value from the string by putting either * or + operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
So, this can be solved in O(n) without using any sorting algorithm.
The simple logic behind the solution is whenever you find "0" or "1" in any of the operands use "+" and the rest of the places use "*".
Here is my solution which got successfully submitted:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int T = Integer.parseInt(scan.nextLine());
while(T-- > 0) {
String str = scan.nextLine();
maxValue(str);
}
}
static void maxValue(String str) {
long maxNumber = 0;
for(int i = 0; i < str.length(); i++) {
int n = Character.getNumericValue(str.charAt(i));
if (maxNumber == 0 || maxNumber == 1 ||
n == 0 || n == 1) {
maxNumber += n;
} else {
maxNumber *= n;
}
}
System.out.println(maxNumber);
}
}
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.println(reverse);
}
}
}
All numbers reverse well but I have problem with reversing numbers that end with zero e.g numbers like 10000 instead of reversing result being 00001 it gives the result as 1 which is not what the question wants is there a way to use integers or string will be the best and easier approach? Thank you
Try the reversing of string concept
String s ="10000";
String n= "";
for(int i=0; i<s.length(); i++){
n = s.charAt(i) + n;
}
System.out.println(n);
You can create a variable length, and use System.out.printf to format output.
With %0 + length + d, it will add 0 on the left to make the output have this length.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
int length = String.valueOf(number).length();
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.printf("%0" + length + "d", reverse);
}
}
}
You could also solve it with a StringBuilder. It already has a method called reverse:
public String reverseInput(int number) {
String s = Integer.toString(number);
return new StringBuilder(s).reverse().toString();
}
You can't have a Integer beginning with 0 except 0 itself. So you will have to work with Strings or other datastructures.
I have a sentence, and I want to find the char that appears in the most words, and how many words it appears in.
For example: "I like visiting my friend Will, who lives in Orlando, Florida."
Which should output I 8.
This is my code:
char maxChar2 = '\0';
int maxCount2 = 1;
for (int j=0; j<strs2.length; j++) {
int charCount = 1;
char localChar = '\0';
for (int k=0; k<strs2[j].length(); k++) {
if (strs2[j].charAt(k) != ' ' && strs2[j].charAt(k) != maxChar2) {
for (int l=k+1; l<strs2[j].length(); l++) {
if (strs2[j].charAt(k)==strs2[j].charAt(l)) {
localChar = strs2[j].charAt(k);
charCount++;
}
}
}
}
if (charCount > maxCount2) {
maxCount2 = charCount;
maxChar2 = localChar;
}
}
, where strs2 is a String array.
My program is giving me O 79. Also, uppercase and lowercase do not matter and avoid all punctuation.
As a tip, try using more meaningful variable names and proper indentation. This will help a lot especially when your program is not doing what you thought it should do. Also starting smaller and writing some tests for it will help a bunch. Instead of a full sentence, get it working for 2 words, then 3 words, then a more elaborate sentence.
Rewriting your code to be a bit more readable:
// Where sentence is: "I like".split(" ");
private static void getMostFrequentLetter(String[] sentence) {
char mostFrequentLetter = '\0';
int mostFrequentLetterCount = 1;
for (String word : sentence) {
int charCount = 1;
char localChar = '\0';
for (int wordIndex = 0; wordIndex < word.length(); wordIndex++) {
char currentLetter = word.charAt(wordIndex);
if (currentLetter != ' ' && currentLetter != mostFrequentLetter) {
for (int l = wordIndex + 1; l < word.length(); l++) {
char nextLetter = word.charAt(l);
if (currentLetter == nextLetter) {
localChar = currentLetter;
charCount++;
}
}
}
}
if (charCount > mostFrequentLetterCount) {
mostFrequentLetterCount = charCount;
mostFrequentLetter = localChar;
}
}
}
Now all I did was rename your variables and change your for loop to a for-each loop. By doing this you can see more clearly your algorithm and what you're trying to do. Basically you're going through each word and comparing the current letter with the next letter to check for duplicates. If I run this with "I like" i should get i 2 but instead I get null char 1. You aren't properly comparing and saving common letters. This isn't giving you the answer, but I hope this makes it more clear what your code is doing so you can fix it.
Here is a somewhat more elegant solution
public static void FindMostPopularCharacter(String input)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
input = input.toUpperCase();
HashMap<Character, Integer> charData = new HashMap<>();
char occursTheMost = 'A'; //start with default most popular char
int maxCount = 0;
//create the map to store counts of all the chars seen
for(int i = 0; i < alphabet.length(); i++)
charData.put(alphabet.charAt(i), 0);
//first find the character to look for
for(int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
//if contained in our map increment its count
if(charData.containsKey(c))
charData.put(c, charData.get(c) + 1);
//check for a max count and set the values accordingly
if(charData.containsKey(c) && charData.get(c) > maxCount)
{
occursTheMost = c;
maxCount = charData.get(c);
}
}
//final step
//now split it up into words and search which contain our most popular character
String[] words = input.split(" ");
int wordCount = 0;
CharSequence charSequence;
for(Character character : charData.keySet())
{
int tempCount = 0;
charSequence = "" + character;
for(int i = 0; i < words.length; i++)
{
if(words[i].contains(charSequence))
tempCount++;
}
if(tempCount > wordCount)
{
occursTheMost = character;
wordCount = tempCount;
}
}
System.out.println(occursTheMost + " " + wordCount);
}
Output of
String input = "I like visiting my friend Will, who lives in Orlando, Florida.";
FindMostPopularCharacter(input);
is
I 8
Note: If there are ties this will only output the character that first reaches the maximum number of occurrences.
FindMostPopularCharacter("aabb aabb aabb bbaa");
Outputs
B 4
because B reaches the max first before A due to the last word in the input.
FindMostPopularCharacter("aab aab b")
B 3