I'm trying to solve a question where your code is supposed to determine if a given number is a palindrome or not, and I don't understand why it isn't working.
(You can skip this and just read the code if you want) The idea was that I create a string with the value of the integer, and create a for loop using the length of said string that uses % 10 to reverse the integer and store it in a separate string. I would then compare the 2 strings to determine if the number is a palindrome or not
public static boolean isPalindrome(int x) {
String s = String.valueOf(x);
int count = s.length();
String palindrome = "";
for(int i = 0; i < count; i++){
palindrome += x % 10;
}
System.out.print(palindrome);
if(palindrome == s){
return true;
}
else{
return false;
}
}
The problem is that the code only returns false, and when I added a print statement to check what the reversed number (String palindrome) is, I got a different number.
For ex. I used 121 to test it and after the for loop the print statement outputted 111.
I'm not really looking for a solution, I just want to understand why it's behaving like this. Thanks in advance.
for(int i = 0; i < count; i++){
palindrome += x % 10;
}
Since x does not change in that loop (or indeed anywhere in the code), each execution yields the same thing, the least significant digit of x.
Thus palindrome has some number of copies of the same digit, and will almost never equal s
You need to divide x by 10 each time around the loop.
Related
the function only returns value when I declare 'n' as int, but returns null when i use 'long'.
Given a string and a value n, the string should be concatenated n number of times. in the concatenated string, we will take the first n characters in that string and return the number of letter 'a' that appeared.
Print a single integer denoting the number of letter a's in the first n letters of the infinite string created by repeating s infinitely many times.
In this function, two parameters are passed, a string and a long value. The code works very well if use an int value instead of long. Please how do i fix this long and int issue ?
public class StringLettersRepeat {
static long repeatedString(String s, long n) {
String string = "";
int count =0;
for(int i=0; i<n; i++){
string+=s;
}
char[] strChar = string.toCharArray();
char[] result = new char[(int) n];
for(int i=0; i<strChar.length;i++){
result[i]=strChar[i];
}
for(char str : result){
if('a'==str){
count++;
}
}
return count;
}
public static void main(String[] args) {
long result = repeatedString("a", 1000l);
System.out.println(result);
}
}
I expect the output to return a value, which is the number of count.
for example, if I enter string "aba" and n=7, it should return 5.
But if i pass in a string, say 'a' with n=100000000000, it's supposed to return 100000000000 but it doesn't work. Please what's possibly wrong with my code?
Given your example of calling repeatedString("aba", 7), the resulting string would be "abaabaa", and has 5 a's, as you said.
But, you don't actually have to build that result string. Instead, realize that the result string is the original string repeated 2 times, plus the first 1 characters of the string, both of which can easily be calculated using division and remainder math:
long repeats = n / s.length();
long extra = n % s.length();
Now, if you count the number of a's in the string, you can multiply by repeats. You don't need to repeat the counting operation. If you then also count the number of a's in the first extra characters of string, you have your final result.
int countFull = 0, countExtra = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'a') {
countFull++;
if (i < extra)
countExtra++;
}
}
Then calculate the total and return it:
return countFull * repeats + countExtra;
This code also runs a lot faster, because you only have to iterate s once, it doesn't matter for performance what n is, and you don't copy any characters, so it also uses a lot less memory. It actually doesn't use any memory.
Big-O is:
Performance: O(m) where m is length of input string.
Memory: O(1)
Neither is related to n.
Test
System.out.println(repeatedString("aba", 7));
System.out.println(repeatedString("a", 100000000000L));
Output
5
100000000000
My friend gave me this code and i cant seem to find the error in it. I am attaching the code below:
import java.util.*;
public class prg {
public static void main(String[] args) {
int n;
int count;
int a=0,b=1;
int c=0;
Scanner kb=new Scanner(System.in);
n=kb.nextInt();
int ar[]=new int[100];
ar[1] = 2;
for(int i=3;i<=n;i+=2)
{
count=0;
for (int j = 2; j < i ;j++ ) {
if (i % j == 0) {
count++;
break;
}
}
if(count==0)
ar[i]=i;
}
for(int i=0;i<=n;i+=2)
{
a = b;
b = c;
c = a + b;
ar[i]=c;
}
for(int i=0;i<14;i++)
System.out.print(ar[i]+" ");
}
}
So, the even index is storing the fibonacci series and the odd index is storing prime number.
Problem: the rest of the code is working fine but the 9th index of 'ar' array is printing 0 i dont know why and because of it the output is showing wrong.
Take input n as 14 and check the code please.
Thankyou in advance.
PS: i have solved this question in one other way so i request you to not give answers like 'try my method, its not efficient'. I just want to know what is going wrong at INDEX 9 of the array.
Edited: facing problem with the Prime Number loop.
When i is 9, your code correctly identifies that it is not a prime number, so count is not 0. This causes this line to not run:
ar[i]=i;
And then you increase i by 2 to check the next odd number. This means that you never set index 9 of the array to anything, so it remains at its default value - 0.
To fix this, you should introduce a new variable possiblePrime to keep track of which number you are checking. Increase this variable every iteration of the outer for loop, and increase i only when possiblePRime is prime. Also, change the above line to:
ar[i] = possiblePrime;
9 is not a prime number, so it sets nothing in the array. 0 is the default value so it gets printed.
I'm trying to solve HackerRank Day Of Code 10.
In short, the task is to find the maximum number of consecutive 1's in the binary representation of a decimal number. In my code I've tried to use two variables: count and hold. count increases by 1 whenever the current position of the string and the previous position are both 1. Whenever the i'th position is 0, count 's value is assigned to the variable hold. In the following iterations if ever the value of count exceeds that of hold then the value of count is assigned to hold. In this way the maximum number of consecutive 1's is stored in hold. Finally I'm printing the value of hold.
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter decimal number");
int n = in.nextInt();
String binary = Integer.toString(n,2);
int count=1;
int hold=0;
if(binary.equals("0"))
System.out.println(0);
else
{
for(int i=0;i<binary.length();i++)
{
if(i==0){}
else if(binary.charAt(i-1)=='1' && binary.charAt(i)=='1')
{
count++;
}
if(count>hold)
hold=count;
if(binary.charAt(i)=='0')
{
hold=count;
count=1;
}
}
System.out.println(hold);
}
}
}
My code isn't working for the sample input "524275" which converts to "1111111111111110011" in binary. The output comes out to be 2 which is strange. my code is written such that the "maximum" number of consecutive 1's are returned. Where did I go wrong? I tried dry running the code mentally but can't spot the mistake yet.
After processing the first 15 ones in with the for loop, hold will actually have the value 15. Then you meet the first zero, and if(binary.charAt(i)=='0') { hold=count; count=1; } will reset count to 1. But then you immediately find another zero, and the same code if(binary.charAt(i)=='0') { hold=count; count=1; } stores 1 in hold and you loose the information 15.
An easy solution is just to remove the line hold=count; in this line. You already set hold three lines above. (And correctly, because you only do it if count is bigger then the previous best value.
The approach is quite complicated. If you want an easier approach. The code should be pretty self-explanatory.
int current_consecutive_ones = 0;
int best_consecutive_ones = 0;
for(int i = 0; i < binary.length(); i++)
{
if (binary.charAt(i) == '1')
current_consecutive_ones++;
else
current_consecutive_ones = 0;
if (current_consecutive_ones > best_consecutive_ones)
best_consecutive_ones = current_consecutive_ones;
}
System.out.println(best_consecutive_ones);
This question already has answers here:
How to find all permutations of a given word in a given text?
(6 answers)
Closed 8 years ago.
This is not same as "How to check if a string contains s specific substring?" . I found a no of questions like that here but not precisely what i am looking for.
I am creating a program at a competitive coding site the problem of which states that we are given a string made of x,y,z and we have to count the number of substrings which contains atleast one of those chars but not all of them.I tried this...
String text = sc.next();
int l = text.length();
int count=0;
for(int j =1;j<=l;j++)
{
for(int i1 =0;i1<j;i1++){
String g = text.substring(i1,j);
if(g.contains("xyz")||g.contains("xzy")||g.contains("yzx")||g.contains("yxz")||g.contains("zxy")||g.contains("zyx"))
;
else
count++;
}
}
System.out.println(count);
And this worked(atleast for 2 test cases). But for the larger test cases my program is violating the time limit. Now i think that is because of the number of matching conditions in the if clause. I would like to know if there is any way by which i can just check if the substring contains 'xyz' in any order instead of checking for every order.Thanks! Any help is appreciated.
P.S- If anything else is responsible for the time limit violation, do mention out !
Here is a simple solution. Warning untested code!
String target = ...
String text = sc.next();
if (target.length() == 0) {
// matched!
} else {
for (int i = 0; i <= text.length() - target.length(); i++) {
if ((pos = target.indexOf(text.charAt(i))) >= 0) {
boolean[] found = new boolean[target.length()];
found[pos] = true;
int matchCount = 1;
outer: for (j = 1; j < target.length(); j++) {
pos = 0;
while (true) {
pos = target.indexOf(text.charAt(i + j), pos);
if (pos == -1) {
break outer;
} else if (!found[pos]) {
found[pos] = true;
matchCount++;
break;
}
}
}
if (matchCount == target.length()) {
// matched!
}
}
}
}
If you wanted to make this faster, one possibility is to clear and recycle the found array that we are using "mark off" the characters as we match them.
There may be more significant optimizations. However, I don't think that the Boyer-Moore "trick" of skipping a number of characters is going to work here.
UPDATE
Your original solution is O(N factorial(M)) where N is the text length, and M is the target string length.
My solution is O(N M).
The optimal solution involves calculating a running hash by multiplying prime numbers, as described in one of the answers to How to find all permutations of a given word in a given text?. I think it is O(N) on average.
(Hint: the solution I'm referring to as written looks like it is O(M N). However, we should be able to use the inverse multiplication equality:
((ab mod n) . (b-1 mod n)) mod n = a mod n
where a and b are the prime factors and n is 232 or 264 depending on whether we use int or long. Reference: wikipedia.
This will allow is to "multiply in" and then "inverse multiply out" the characters and therefore update the running hash in O(1) operations.)
I've looked at a few different stack questions and googled, but nothing I've read really has dealt with reversal of integers, but just strings.
So right now my code may or may not work at all, and it may be the dumbest thing you've ever seen, and that's okay and corrections are welcomed, but from what I hope my code will be doing is going through 100 - 999 multiplying the two ints and then checking whether it's palindromic or not. The if with reverse.equals(sum) is totally pseudocode and obviously won't work, however I can't figure out how to do a check for a palindromic int. Is there a simple way to do this? I've read some pretty lengthy and complicated ways, but I'm sure there's gotta be a simple way. Maybe not. :/. Anyway, here's my code.
public class PalandromicNum {
public static void main(String[] args){
int numOne = 100;
int numTwo = 100;
int toteVal;
int counter = 1000;
int sum = 0;
int finalSum = 0;
for(int i=0; i<counter; i++){
toteVal = numOne * numTwo;
numTwo++;
if(numTwo == 999){
numOne++;
numTwo = 100;
}
if(toteVal < sum){
sum += toteVal;
if(reverse.equals(sum)){
finalSum = sum;
System.out.println(finalSum);
}
}
}
}
}
Thanks again in advance!
This is on my phone so sorry for any errors.
Convert your number to a String and:
public static boolean isPalindrome(String str)
{
// base recursive case
if (str.length <= 1) {
return true;
}
// test the first and last characters
char firstChar = str.charAt(0);
char lastChar = str.charAt(str.length - 1) // subtract 1 as indexes are 0 based
if (!firstChar.equals(lastChar)) {
return false;
}
// if the string is longer than 2 chars and both are equal then recursively call with a shorter version
// start at 2nd char, end at char before last
return isPalindrome(str.substring(1,str.length);
}
Reversing integers is quite easy. Remember mod 10 gives u last digit. Loop over it, chopping off last digit of the number one at a time and adding it to reverse to new number. Then its matter of simple integer equality
int rev = 0;
int n = sum;
while(n)
{
rev = rev*10 + n%10;
n /= 10;
}
if(sum==rev)
//palindrome
else
//no no no no.
You can create a function named isPalindrome to check whether a number is a palindrome.
Use this function in your code.
You just need to pass the number you want to check into this function.
If the result is true, then the number is a palindrome.
Else, it is not a palindrome.
public static boolean isPalindrome(int number) {
int palindrome = number; // copied number into variable
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// if original and reverse of number is equal means
// number is palindrome in Java
if (number == reverse) {
return true;
}
return false;
}
}
I believe that this code should help you out if you are trying to find out how many palindromes are between 100-999. Of course, it will count palindromes twice since it looks at both permutations of the palindromes. If I were you I would start creating methods to complete a majority of your work as it makes debugging much easier.
int total = 100;
StringBuilder stringSumForward;
StringBuilder stringSumBackward;
int numberOfPals = 0;
for(int i = 100; i < 999; i++){
for(int j = 100; j < 999; j++){
total = i * j;
stringSumForward = new StringBuilder(String.valueOf(total));
stringSumBackward = new StringBuilder(String.valueOf(total)).reverse();
if(stringSumForward.toString().equals(stringSumBackward.toString())){
numberOfPals++;
}
}
}