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;
}
Related
The code below has no output when I run it, I think somehow it is infinite loop? How to fix it?
Write a method named getEvenDigitSum with one parameter of type int called number.
The method should return the sum of the even digits within the number.
If the number is negative, the method should return -1 to indicate an invalid value.
EXAMPLE INPUT/OUTPUT:
getEvenDigitSum(123456789); → should return 20 since 2 + 4 + 6 + 8 = 20
getEvenDigitSum(252); → should return 4 since 2 + 2 = 4
getEvenDigitSum(-22); → should return -1 since the number is negative
public class getEvenDigitSum {
public static int getEvenDigitSum(int number) {
int sum = 0;
int lastDigit=0;
if (number < 0) {
return -1;
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
return sum;
}
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
OK, and what happens if the number isn't even? You didn't make an else/else if statement after; if your number is odd, it stays the same, the loop is infinite, and hence your code does nothing.
Your condition only handles even digits, but think about what happens when you get a number that contains odd digit, like 1221 for example.
Try adding the missing else statement:
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
else {
// Deal with odd digit, leaving for you to implement
{
}
General tip: The best way to find errors in your code is to write tests and debug your code.
These are two skills every developer should poses and practice regularly
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.
Currently doing a challenge called number to words, I have created 2 methods, one which
deals with comparing values individually so that it can print out it's string value(method called numberToWord), another method called reverse which basically re-orders the values so that it is printed in a correct sequence, for example:s
Step One 567 --> Step 2, it will be converted into 765 --> Step 3, reverse method will then convert it back to 5,6,7 individually so that it can compare the values with the if statements. However, i have tried so many things to getting this to work, i managed to make it to step 3 but when i try to return the value it gives me 3 random values before it converts e.g = 7,6,7...5,6,7, i am unable to figure out how to remove the first 3 values and return just the last three values so that it can be compared in the numberToWords method.
package com.company;
public class Main {
public static void main(String[] args) {
numberToWords(567);
}
public static void numberToWords(int number) {
int lastDigit = 0;
int digit = number;
int reverseDigit = 0;
if (number < 0) {
System.out.println("Invalid Value");
}
for (int i = 0; i < digit; i++) {
//so we are taking the last digit from 567 per iteration
lastDigit = digit % 10;
//we are then dividing the digit by 10 each time so we can get another last digit
digit /= 10;
//i will now try to essentially get down to the final number which will be flipped
reverseDigit = (reverseDigit * 10) + lastDigit;
//checking values
System.out.println(reverse(reverseDigit));
// if (reverse(reverseDigit)== 0) {
// System.out.println("Zero");
// } else if (reverse(reverseDigit) == 1) {
// System.out.println("One");
// }else if (reverse(reverseDigit) == 2) {
// System.out.println("Two");
// }else if (reverse(reverseDigit) == 3) {
// System.out.println("Three");
// }else if (reverse(reverseDigit) == 4) {
// System.out.println("Four");
// }else if (reverse(reverseDigit) == 5) {
// System.out.println("Five");
// }else if (reverse(reverseDigit) == 6) {
// System.out.println("Six");
// }else if (reverse(reverseDigit) == 7) {
// System.out.println("Seven");
// }else if (reverse(reverseDigit) == 8) {
// System.out.println("Eight");
// }else if (reverse(reverseDigit) == 9) {
// System.out.println("Nine ");
// }
if (lastDigit == 0) {
System.out.println("Zero");
} else if (lastDigit == 1) {
System.out.println("One");
} else if (lastDigit == 2) {
System.out.println("Two");
} else if (lastDigit == 3) {
System.out.println("Three");
} else if (lastDigit == 4) {
System.out.println("Four");
} else if (lastDigit == 5) {
System.out.println("Five");
} else if (lastDigit == 6) {
System.out.println("Six");
} else if (lastDigit == 7) {
System.out.println("Seven");
} else if (lastDigit == 8) {
System.out.println("Eight");
} else if (lastDigit == 9) {
System.out.println("Nine");
}
}
}
public static int reverse (int a){
int lastDigit = 0;
for (int i =0; i < a; i++) {
lastDigit = a % 10;
a /= 10;
//testing values here
//System.out.println(lastDigit);
//sout in loop gives us 567
}
return lastDigit;
}
}
If I understand what you need correctly, you don't need that much code. Just print the reminder of division by 10 and then divide by ten for then next iteration until you get zero.
enum Numbers {
Zero,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine;
}
private static void process(int number) {
do {
final int digit = number % 10;
System.out.println(Numbers.values()[digit]);
number /= 10;
} while (number > 0);
}
First use an enum since you can use it like an array but easier to declare. Then with the number you get, first get the reminder over ten. For any integer expressed as decimal the reminder over ten is the last digit. Since you have to print the last digit in the first place, just print it. Then replace number with number divided by ten. That will discard the last digit (the one just printed out) because this is an integer division. I mean, 1234 over 10 is 123.4 but because these are integer it gets truncated to 123. So now loop and the last digit will be printed again (but now it will be the first to the left due to the division). At some point, after printing the first digit of the original number you will have a one digit integer (i.e. 7) divided by ten which results in zero (because it would be 0.7 but it's an integer division).
You need to add some preconditions like the negatives.
I think you have the right idea of doing remainder division for numberToWords() and reverse().
But I think you're condition for exiting the for loop is wrong
for (int i = 0; i < digit; i++)
It will exit before you get all the digits. You want to loop until digit is 0, since you want to remainder divide UNTIL there's no more to divide ( meaning digit is 0).
so
for(int i = 0; digit != 0; i++){
...
}
while loop might be better than a for a loop since you're not using i anyways.
while(digit != 0){
...
}
It also depends on which IDE you're using but IntelliJ and eclipse can do a line by line debug so you see which line is causing issues.
I have this exercise that asks me to create a program to count the odd digits of a number, so if the number is 12345 it will count to 3, because of 1, 3 and 5. I started creating a recursive method, my very first one, with a ramified if-else. The point of using it was to see if (inputNumber % 2 == '0'). If yes, the last digit of the number would be a 0, 2, 4, 6 or 8, because only those digits give 0 if moduled by 2, so oddDigitsCounter wouldn't grow. Else, if (inputNumber % 2 == '1'), the last digit of the number would be 1, 3, 5, 7 or 9. oddDigitCounter++;, so. To check digit by digit I tried to divide the number by ten because it is a int variable, so it doesn't saves any digit after the floating point.
This is the method since now:
public static int oddDigitCounter (int number) {
int oddCount, moduledNumber, dividedNumber, absoluteInput;
oddCount = 0;
absoluteInput = Math.abs(number);
moduledNumber = absoluteInput % 2;
dividedNumber = absoluteInput / 10;
if (absoluteInput == '0') {
oddCount = oddCount; }
else if (moduledNumber == '0') {
oddCount = oddCount;
oddDigitCounter(dividedNumber); }
else // (number % 2 != 0)
oddCount++;
oddDigitCounter(dividedNumber); }
return oddCount;
Why it gives me an infinite recursion? What's wrong? Why? Any other way to solve this? Any idea for improving my program?
You don't use the result of the recursive call. You also compared a integer to the character '0', which is not the same as comparing to 0.
public static int oddDigitCounter (int number)
{
int moduledNumber, dividedNumber, absoluteInput;
inputAssoluto = Math.abs(numero);
moduledNumber = absoluteInput % 2;
dividedNumber = absoluteInput / 10;
if (absoluteInput == 0) {
return 0;
}
else if (moduledNumber == 0) {
return oddDigitCounter(dividedNumber);
}
else {
return 1 + oddDigitCounter(dividedNumber);
}
}
Declare odd counter outside of recursion and you should get results :
static int oddCounts;
public static int oddDigitCounter(int number) {
int moduledNumber, dividedNumber, absoluteInput = 0;
absoluteInput = Math.abs(number);
moduledNumber = absoluteInput % 2;
dividedNumber = absoluteInput / 10;
if (absoluteInput == 0) {
return 0;
} else if (moduledNumber == 0) {
return oddDigitCounter(dividedNumber);
} else {
oddCounts++;
return 1 + oddDigitCounter(dividedNumber);
}
}
As mentioned in the comments, you should compare to 0 and not to '0'. The latter will be interpreted as 48, the ASCII character for the numeral zero.
Furthermore, absoluteInput is never assigned to and will always have its initial value 0. Where does inputAssoluto come from?
Wouldn't you want to list your numbers and then check each one as a single int again, meaning you can check digit by digit and don't have to divide the number by ten.
a very short solution will then suffice: (if your passing the number as a string the LINQ one-liner can give you what you want).
static int OddDigitCounter(int numbers)
{
var c = numbers.ToString();
var oddcount = c.Count(no => int.Parse(no.ToString()) % 2 != 0); //<--one liner
return oddcount;
}
Was asked this question recently and did not know the answer. From a high level can someone explain how Java takes a character / String and convert it into an int.
Usually this is done like this:
init result with 0
for each character in string do this
result = result * 10
get the digit from the character ('0' is 48 ASCII (or 0x30), so just subtract that from the character ASCII code to get the digit)
add the digit to the result
return result
Edit: This works for any base if you replace 10 with the correct base and adjust the obtaining of the digit from the corresponding character (should work as is for bases lower than 10, but would need a little adjusting for higher bases - like hexadecimal - since letters are separated from numbers by 7 characters).
Edit 2: Char to digit value conversion: characters '0' to '9' have ASCII values 48 to 57 (0x30 to 0x39 in hexa), so in order to convert a character to its digit value a simple subtraction is needed. Usually it's done like this (where ord is the function that gives the ASCII code of the character):
digit = ord(char) - ord('0')
For higher number bases the letters are used as 'digits' (A-F in hexa), but letters start from 65 (0x41 hexa) which means there's a gap that we have to account for:
digit = ord(char) - ord('0')
if digit > 9 then digit -= 7
Example: 'B' is 66, so ord('B') - ord('0') = 18. Since 18 is larger than 9 we subtract 7 and the end result will be 11 - the value of the 'digit' B.
One more thing to note here - this works only for uppercase letters, so the number must be first converted to uppercase.
The source code of the Java API is freely available. Here's the parseInt() method. It's rather long because it has to handle a lot of exceptional and corner cases.
public static int parseInt(String s, int radix) throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, max = s.length();
int limit;
int multmin;
int digit;
if (max > 0) {
if (s.charAt(0) == '-') {
negative = true;
limit = Integer.MIN_VALUE;
i++;
} else {
limit = -Integer.MAX_VALUE;
}
multmin = limit / radix;
if (i < max) {
digit = Character.digit(s.charAt(i++), radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
} else {
result = -digit;
}
}
while (i < max) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++), radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
if (negative) {
if (i > 1) {
return result;
} else { /* Only got "-" */
throw NumberFormatException.forInputString(s);
}
} else {
return -result;
}
}
I'm not sure what you're looking for, as "high level". I'll give it a try:
take the String, parse all characters one by one
start with a total of 0
if it is between 0 and 9, total = (total x 10) + current
when done, the total is the result
public class StringToInt {
public int ConvertStringToInt(String s) throws NumberFormatException
{
int num =0;
for(int i =0; i<s.length();i++)
{
if(((int)s.charAt(i)>=48)&&((int)s.charAt(i)<=59))
{
num = num*10+ ((int)s.charAt(i)-48);
}
else
{
throw new NumberFormatException();
}
}
return num;
}
public static void main(String[]args)
{
StringToInt obj = new StringToInt();
int i = obj.ConvertStringToInt("1234123");
System.out.println(i);
}
}
Find the length of the String (s) (say maxSize )
Initialize result = 0
begin loop ( int j=maxSize, i =0 ; j > 0; j--, i++)
int digit = Character.digit(s.charAt(i))
result= result + digit * (10 power j-1)
end loop
return result
this is my simple implementation of parse int
public static int parseInteger(String stringNumber) {
int sum=0;
int position=1;
for (int i = stringNumber.length()-1; i >= 0 ; i--) {
int number=stringNumber.charAt(i) - '0';
sum+=number*position;
position=position*10;
}
return sum;
}
Here is what I came up with (Note: No checks are done for alphabets)
int convertStringtoInt(String number){
int total =0;
double multiplier = Math.pow(10, number.length()-1);
for(int i=0;i<number.length();i++){
total = total + (int)multiplier*((int)number.charAt(i) -48);
multiplier/=10;
}
return total;
}
Here is my new approach which is not in a math way.
let n = 12.277;
// converting to string
n = n.toString();
let int = "";
for (let i = 0; i < n.length; i++) {
if (n[i] != ".") {
int += n[i];
} else {
break;
}
}
console.log(Number(int));