This is my task:
Given a string, does "xyz" appear in the middle of the string? To define middle, we'll say that the number of chars to the left and right of the "xyz" must differ by at most one.
The problem description and the failures in others use case can be seen by using the code below here
xyzMiddle("AAxyzBB") → true
xyzMiddle("AxyzBB") → true
xyzMiddle("AxyzBBB") → false
My solution is below. Since I can't see what 'other tests' are, please help me spot the problem. My method is to check if 'y' appears in the middle for odd or even a String.
public boolean xyzMiddle(String str) {
if (str.indexOf("xyz") < 0) return false;
int l = str.length();
int m = l / 2;
if (l % 2 != 0) {
if (str.charAt(m) != 'y') return false;
}
else {
if (str.charAt(m) != 'y' && str.charAt(m - 1) != 'y') return false;
}
return true;
}
The problem with your solution is that you are simply returning false in case the string in question has odd length
Which is actually not true, the pass use-cases for this task can be mathematically divided like below:
1)With xyz present in the middle and there is a string of length x + 1 and x to either the left or right of it.
taking length of string xyz as 3 the total length comes out to be:
(x) + 3 + (x + 1) = 2x + 4 --->Always even
so in the case above we just check is xyz is in the middle or not and return accordingly which is already handled in your code.
2) With xyz present in the middle and there are strings of length x to the left or right of it.
Again taking length of string xyz as 3 the total length comes out to be:
(x) + 3 + (x) = 2x + 3 --->Always odd
Hence as per your solution to return true in this case(last line of code) you need to filter out the cases when length is odd but xyz is not in the middle as below:
if (!(str.substring((m - 1), m + 2).equals("xyz")))
return false;
With this included your solutions looks like as below:
public boolean xyzMiddle(String str) {
if (str.indexOf("xyz") < 0) return false;
int l = str.length();
int m = l / 2;
if (l % 2 != 0) {
if (!(str.substring((m - 1), m + 2).equals("xyz")))
return false;
}
else {
if (str.charAt(m) != 'y' && str.charAt(m - 1) != 'y') return false;
}
return true;
}
Now it passes all the tests on codingBat.
if(str.length() <3) return false;
int ind = str.indexOf("xyz", str.length()/2 - 3) ;
String first = str.substring(0, ind);
String second = str.substring(ind+3);
return (first.length() == second.length() || first.length() +1 == second.length() || first.length() == second.length() + 1);
Related
I want to check if a number if binary or not in decimal numbers but it didnt work
from numbera 1 to n.
for example from 1 to 10 we have 2 decimal numbers that contains 0,1.How can i change it?
import java.util.Scanner;
public class Main
{
public static void main(String args[]) {
int r = 0, c = 0, num, b;
int count=0;
Scanner sl = new Scanner(System.in);
System.out.println("Enter a number");
num = sl.nextInt();
for (int i = 1; i <= num; i++) {
if ((i % 10 == 0) || (i % 10 == 1))
c++;
r++;
i = i / 10;
}
if (c == r)
count++;
else{
}
System.out.println(count);
}
}
I am not a java dev so maybe my answer is not good.But you can use your number as str then check if the str is constituted only by 0 and 1
maybe this could help: : How to check if only chosen characters are in a string?
have a nice day
Here's how you can do it in an elegant way ...
// Function to check if number
// is binary or not
public static boolean isBinaryNumber(int num)
{
if(num == 1 || num == 0) return true
if (num < 0) return false;
// Get the rightmost digit of
// the number with the help
// of remainder '%' operator
// by dividing it with 10
while (num != 0) {
// If the digit is greater
// than 1 return false
if (num % 10 > 1) {
return false;
}
num = num / 10;
}
return true;
}
Here, will use 2 loops, one for range and one for checking if it's binary or not.
Instead of c and r, we will use flag and break in order to skip unnecessary iteration.
int count=0;
boolean flag = true;
for(int i=1;i<=num;i++)
{
for(int j=i;j>0;j=j/10)
{
// if remainder is not 0 and 1, then it means it's not binary
// so we set flag as false
// and using break to break out of the current(inner) loop, it's no longer needed to check remaining digits.
if (j%10 > 1)
{
flag = false;
break;
}
}
// if flag is true, that means it's binary and we increment count.
// if flag is flase, that means it's not binary
if(flag)
count++;
// here we reset flag back to true
flag = true
}
System.out.println(count);
You can also do as #jchenaud suggested. converting it to string and check if it only contains 0 and 1.
Write a method extractOddDigits() which extracts the odd digits from a positive number n, and
combines the odd digits sequentially into a new number. The new number is returned back to the
calling method. If the input number n does not contain any odd digits, then returns -1.
For examples, if
n=1234567, then 1357 is returned; and if n=28, then –1 is returned.
Test cases:
(1) n : 12345;
(2) n : 54123;
(3) n : 246;
(4) n : -12 (give an error message)
Expected outputs:
(1) oddDigits = 135;
(2) oddDigits = 513;
(3) oddDigits = -1;
(4) oddDigits = Error input!!
This is the method i have done, but the output is
(1) oddDigits = 135;
(2) oddDigits = 513;
(3) oddDigits = -1;
(4) oddDigits = -1
The last output should be Error input!
public static long extractOddDigits(long n){
String output = "";
if(n < 0) // check if negative
{
output = "Error Input!!";
}
if(n % 2 == 0){ //check even
output = "-1";
}
while(n > 0) {
int left = (int) (n % 10);
if(left % 2 != 0)
output = left + output;
n /= 10;
}
System.out.println("oddDigit = " + output);
}
How to i check if n is a negative number then goes to Error input?
Your problem is that the first two if may assign a value to output, but not in a exclusive way, you can find a numer which is negative AND is also even AND it contains odd numbers. So you must ensure your code isolates each option.
Besides, your requirements say that the method must return the number, not just print it, so you method should be returning long and not void, but I'll leave that as part of your homework ;)
public static void extractOddDigits(long n){
String output = "";
if(n < 0) {
output = "Error Input!!";
} else {
while(n > 0) {
int left = (int) (n % 10);
if (left % 2 != 0) {
output = left + output;
}
n /= 10;
}
}
if (output.equals("") {
output="-1";
}
System.out.println("oddDigit = " + output);
}
First of all just because number is even, it does not imply that it does not contain any odd digits.
So:
if(n % 2 == 0){ //check even
output = "-1";
}
is wrong. Also you dont need to type cast the (n % 10); to int.
You can keep a boolean variable foundOdd, that keeps track of whether so far we have found any odd digits, and in the end if that remains false, we can simply print -1.
So the right code is:
int n = 246;
String output="";
boolean foundOdd=false;
if(n < 0) // check if negative
output = "Error Input!!";
else
{
while(n > 0)
{
int left = (n % 10);
if(left % 2 != 0)
{output = left + output; foundOdd = true;}
n /= 10;
}
}
if(foundOdd)
System.out.println("oddDigit = " + output);
else System.out.println(-1);
The problem is:
when n=-12, you are assigning output "Error Input!!"
and then since also n%2==0, you are overwriting output to "-1"
Also, your logic - if n is divisible by 2 , it will not have odd digits, is incorrect
This code checks for all digits if it contains any even one.
public static void extractOddDigits(long n){
String output = "";
if(n < 0) // check if negative
{
output = "Error Input!!";
}
else {
//Iterate through the digits
while(n>0){
long lastDigit = n%10;
if(lastDigit % 2 != 0) { //for odd digit
output = lastDigit+output;
}
n = n/10;
}
}
//If no odd digits
if(output.equals("")) {
output = "-1";
}
System.out.println(output);
}
If you do not want the method to run further if n < 0, then ,
if(n < 0) // check if negative
{
output = "Error Input!!";
System.out.println(output);
return;
}
So i have a string in military time format : "1532" corresponding to 3:32pm.
I'm trying to write a method to check if each digit in time string is an appropriate digit. So the first element cannot be greater than 2 or equal to 0, and so forth. Currently, my code doesn't run past the second log statement and I'm hoping you guys could help!
cheers!
String mOpen = "1532";
Log.d("hoursTesting","pass1, length is > 2");
if(mOpen.getText().length() == 4)
{
Log.d("hoursTesting","pass2, length is == 4");
char[] tempString = mOpen.getText().toString().toCharArray();
if(tempString[0] != 0 && tempString[0] < 3)
{
Log.d("hoursTesting","pass3, first index is != 0 and < 3");
if(tempString[0] == 1)
{
Log.d("hoursTesting","pass4, first index is 1");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass5, third index is <= 5, success!");
}
}
else //tempString[0] is equal to 2
{
Log.d("hoursTesting","pass4, first index is 2");
if(tempString[1] < 4)
{
Log.d("hoursTesting","pass5, second index is <3");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass6, third index is <= 5, success!");
}
}
}
}
}
tempString contains characters, not numbers.
i.e. '0' not 0 etc.
Easiest fix is to compare characters e.g. tempString[0] == '1' Alternatively, you can do something like int digit1 = tempString[0] - '0'; - but that kind of assumes you already know you just have digits in the string.
Note that cos of those clever ASCII guys and their tricky character set '0' < '1' < '2' etc, so you can still say if (str[0] < '2') etc. You just need to be a bit careful that you are only dealing with digits.
Personally I'd convert the first 2 chars to a number and the second 2 chars to a number and then just check 0 <= number1 <= 23 and 0 <= number2 <= 59.
You are comparing char with int here:
if(tempString[0] != 0 && tempString[0] < 3)
It should work like this:
if(tempString[0] != '0' && tempString[0] < '3')
I would substring the hours and minutes components and then check to see if each one be in range:
public boolean isTimeValid(String mOpen) {
int hours = Integer.parseInt(mOpen.substring(0, 2));
int minutes = Integer.parseInt(mOpen.substring(2));
if ((hours >= 0 && hours <= 24) && (minutes >= 0 && minutes <= 59)) {
return true;
}
else {
return false;
}
}
I am trying to solve this : Given an integer, return 1 if the number is between -5 and 5 exclusive and/or if it is an odd integer. If neither properties apply, return 0.
Here is what I have tried:
int rangeOrOdd(int val) {
if (val < 5)
return 1;
else if (val > 5)
return 1;
else if ((val%2)!=0)
return 0;
else
return 0;
}
The problem is that you are checking the different conditions individually. For instance, as soon as your number is smaller than 5, you return 1, which is wrong, because you would then return 1 for numbers like -1000.
Also, you are returning 0 for an odd number. You were supposed to return 1 in that case.
You have to combine your conditions using ANDs (&&) and ORs (||).
Here is a one liner that combines the different conditions correctly:
return ((val < 5 && val > -5) || val % 2 == 1) ? 1 : 0;
And if you don't like it in one line, you can always split it like this (but it's the same thing):
if ((val < 5 && val > -5) || val % 2 == 1) {
return 1;
} else {
return 0;
}
I read a book about challenges in Java, and it gives the next question:
create a function, which get a number as argument, and detect if number is a multiple of 7 or contains the number 7.
The signature is: public boolean find7(int num)
I create this function, when the number is between 0 to 99, by the next condition:
if (num mod 7 == 0 || num / 10 ==7 || num mod 10 == 7)
return true;
But what with number which is greater than 99? like 177, or 709? How can I detect it?
It's probably best to leave strings out of this:
public static boolean check(final int n) {
int m = Math.abs(n);
while (m > 0) {
if (m % 10 == 7)
return true;
m /= 10;
}
return n % 7 == 0;
}
The while-loop checks each digit and tests if it is 7; if it is, we return true and if it isn't, we continue. We reach the final return statement only if none of the digits were 7, at which point we return whether the number is a multiple of 7.
if (num % 7 ==0 || ("" + num).contains("7") ){
return true;
}
You can extend your approach to numbers above 100 like this:
public boolean find7(int num) {
// support for negative integers
num = Math.abs(num);
// check if num is a multiple of 7
if (num % 7 == 0) {
return true;
}
// check to see if num contains 7
while (num > 1) {
// if the last digit is 7, return true
if (num % 10 == 7) {
return true;
}
// truncate the last digit
num /= 10
}
// the number is not a multiple of 7 and it does not contain 7
return false;
}
You can do the following
if(Integer.toString(num).contains("7") || ...){
}
As far as checking if the number is divisible by 7, you're fine.
If you want to check if it contains the 7 digit, I think the easiest approach would be to treat the number as a String:
public boolean find7(int num) {
// check if it's a multiple of 7:
if (num % 7 == 0) {
return true;
}
// if it's not, check if it contains the character 7:
return String.valueOf(num).contains("7");
}
For detecting if number is multiple of 7:
boolean isMultiple = x % 7 == 0
For detecting digit:
Convert it to String and use String.contains()
or
Create digit List like this:
private List<Integer> getDigitList(int number){
List<Integer> list = new ArrayList<Integer>();
int leftover = number;
while (leftover != 0){
int result = leftover % 10;
leftover = (leftover - result)/10;
list.add(result)
}
assert leftover == 0;
return list;
}