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.
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.
In my computer science class, we were assigned a lab on recursion in which we have to print out a number with commas separating groups of 3 digits.
Here is the text directly from the assignment (the method has to be recursive):
Write a method called printWithCommas that takes a single nonnegative
primitive int argument and displays it with commas inserted properly.
No use of String.
For example printWithCommas(12045670); Displays 12,045,670
printWithCommas(1); Displays 1
I am really stumped on this. Here is my code so far:
public static void printWithCommas(int num) {
//Find length
if (num < 0) return;
int length = 1;
if (num != 0) {
length = (int)(Math.log10(num)+1);
}
//Print out leading digits
int numOfDigits = 1;
if (length % 3 == 0) {
numOfDigits = 3;
}
else if ((length+1) % 3 == 0) {
numOfDigits = 2;
}
System.out.print(num / power(10,length-numOfDigits));
//Print out comma
if (length > 3) {
System.out.print(',');
}
printWithCommas(num % power(10,length-numOfDigits));
}
It gets a stack overflow (which I can fix later), but it fails to print out some of the zeros, specifically the ones that are supposed to be after each comma.
I feel like I am taking this on with a completely wrong approach, but can't think of a good one. Any help would be appreciated.
Thanks in advance!
Note: power is a function I made that calculates power. First argument is the base, second is the exponent.
Here is the code I came up with, for anyone else that might be stuck on this:
public static void printWithCommas(int num) {
if (num > 999) {
printWithCommas(num/1000);
System.out.print(',');
if (num % 1000 < 100) System.out.print('0');
if (num % 1000 < 10) System.out.print('0');
System.out.print(num%1000);
}
else {
System.out.print(num);
}
}
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;
}
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;
}