Print numbers in Words [duplicate] - java

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
I am trying to print numbers in words. The code I have written is pretty much covering a lot of scenarios but not this: 100 (or 10). It should print One Zero Zero but its only printing one. Can someone please help.
public static void numberToWords (int number) {
if (number < 0) {
System.out.println("Invalid Value");
}
if (number==0){
System.out.println("Zero");
}
number = reverse(number);
int modulus = 0;
while (number > 0) {
if (number % 10 == 0) {
System.out.println("Zero"); } else if (number % 10 == 1) { System.out.println("One"); } else if (number % 10 == 2) {
System.out.println("Two"); } else if (number % 10 == 3) { System.out.println("Three");} else if (number % 10 == 4) {
System.out.println("Four");} else if (number % 10 == 5) { System.out.println("Five");} else if (number % 10 == 6) {
System.out.println("Six");} else if (number % 10 == 7) { System.out.println("Seven");} else if (number % 10 == 8) {
System.out.println("Eight");} else if (number % 10 == 9) { System.out.println("Nine");}
number/=10;
}
}
public static int reverse (int number) {
int reverse = 0;
while (number != 0) {
int lastdigit = (number % 10);
reverse*=10;
reverse +=lastdigit;
number/=10;
}
return reverse;
}
public static int getDigitCount (int number) {
if (number < 0) {
return -1;
}
if (number==0){
return 1;
}
int count = 0;
int last = 0;
while (number > 0) {
last = number % 10;
count++;
number/=10;
}
return count;
}

When you reverse 100, it becomes 1. so you output it "one".
Instead of doing all this thing, Just convert the number into a string and then char array. And then loop on this array

Related

count number of digit using recursive method

Given a non-negative int n, compute recursively (no loops) the count of the occurrences of 8 as a digit, except that an 8 with another 8 immediately to its left counts double, so 8818 yields 4. Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).
count8(8) → 1
count8(818) → 2
count8(8818) → 4
my program seems not able to count double '8's. Here's the code.
public int count8(int n) {
boolean flag = false;
if(n<10)
{
if (n==8)
{
if(flag == true)
return 2;
else
{
flag = true;
return 1;
}
}
else
{
flag = false;
return 0;
}
}
else
return count8(n%10)+count8(n/10);
}
I was wondering if the last line goes wrong but I don't know how to check it. Looking forward to your help. Thanks!
Pass the state (is the previous digit eight) to the method:
private static int count8(int n, boolean eight) {
if (n <= 0)
return 0;
else if (n % 10 == 8)
return 1 + (eight ? 1 : 0) + count8(n / 10, true);
else
return count8(n / 10, false);
}
public static int count8(int n) {
return count8(n, false);
}
Your flag variable is only local. There's only one time you read it: if (flag == true) and since you never change it's value before that it will always be false.
You make this a lot more complicated than it has to be though. No need for an additional parameter at all.
public int count8(int n)
{
if (n % 100 == 88) return count8(n/10) + 2;
if (n % 10 == 8) return count8(n/10) + 1;
if (n < 10) return 0;
return count8(n/10);
}
You can try smth like this:
public int count8(int n) {
if (n < 10)
return n == 8: 1 ? 0;
int count = 0;
String num = Integer.toString(n);
int numLength = num.length();
if (numLength % 2 != 0)
num += "0";
if ((num.charAt(numLength / 2) == num.charAt(numLength / 2 - 1)) && (num.charAt(numLength / 2) == "8"))
count++;
String left = num.substring(0, numLength / 2);
int leftInt = Integer.parseInt(left);
String rigth = num.substring(numLength / 2);
int rigthInt = Integer.parseInt(rigth);
return count + count8(leftInt) + count8(rigthInt);
}
C++
int count8(int n) {
return n == 0 ? 0 : (n % 10 == 8) + (n % 100 == 88) + count8(n/10);
}
Java & C#
int count8(int n) {
if (n==0) return 0;
if(n % 100 == 88)
return 2 + count8(n / 10);
if(n % 10 == 8)
return 1 + count8(n / 10);
return count8(n / 10);
}

Checking if number is ugly

I'm doing this problem:
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
Here's my attempt:
public class Solution {
public boolean isUgly(int num) {
if (num == 1) {
return true;
}
for (int i = 7; i <= num / 2; i++) {
if (isPrimeFactor(i, num)) {
return false;
}
}
return true;
}
public boolean isPrimeFactor(int candidate, int num) {
return isPrime(candidate) && isFactor(candidate, num);
}
public boolean isPrime(int num) {
if (num == 2) {
return true;
}
if (num % 2 == 0) {
return false;
}
for (int i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public boolean isFactor(int candidate, int num) {
return (num % candidate == 0);
}
}
Unfortunately, it fails on test input -2147483648. It returns true when it should be false.
Any idea what I've done wrong?
You simply forgot the following emphasized condition:
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Therefore, you just need to add a check for negative numbers inside your isUgly method:
if (num <= 0) {
return false;
}
As a side-note, you could perhaps improve a little the performance by swapping the conditions inside isPrimeFactor and testing isFactor(candidate, num) && isPrime(candidate) instead of isPrime(candidate) && isFactor(candidate, num). This is because it is faster to determine whether a number is a factor of another than determining if a number is a prime number.
I could propose a different but a lot faster solution O(logn) for this problem:
public static boolean isUgly(int num) {
if (num < 1) return false;
int temp;
do {
temp = num;
if (num % 2 == 0) num /= 2;
if (num % 3 == 0) num /= 3;
if (num % 5 == 0) num /= 5;
} while (temp != num);
return num == 1;
}
or an even faster approach in terms of modular checks (by splitting the do while loop):
public static boolean isUgly(int num) {
if (num < 1) return false;
int temp;
do {
temp = num;
if (num % 2 == 0) num /= 2;
} while (temp != num);
do {
temp = num;
if (num % 3 == 0) num /= 3;
} while (temp != num);
do {
temp = num;
if (num % 5 == 0) num /= 5;
} while (temp != num);
return num == 1;
}

Trouble with factor generator

I'm having some trouble in completing this factor generator from my programming class. It's supposed to take a number, and print out all the factors using the nextFactor method. When I set the number to factor to let's say 150, it prints out "1 2 3 5", where it's supposed to print "2 3 5 5". So, where should I go from here? I've looked at Java - Factor Generator program nextfactor method, but it didn't awnser any of my inqueries
public class FactorGenerator
{
//user inputs int from scanner in FactorTester class
public FactorGenerator(int i)
{
num = i;
}
//Checks to see if num can be factored, but does not factor it.
//Goes through all possible factors of num and returns true if the remainder == 0
public boolean hasMoreFactors()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
return true;
}
}
return false;
}
//Actually factors num and prints out the factor at the end of every loop.
public void nextFactor()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
private int num;
}
try this factors can duplicate so you need to loop until you have extracted all the instances of that factor
public void nextFactor()
{
for(int i = 2; i <= num; i++)
{
//check if the remainder is anything other then 0
while (num >= i && num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
an alternative way is to do the increment in the body of the loop
public void nextFactor()
{
for(int i = 2; i <= num;)
{
//check if the remainder is anything other then 0
if (num % i == 0)
{
System.out.println(i);
num /= i;
} else {
i++;
}
}
System.out.println("Done.");
}
For starters, it will always print out 1 because any integer / 1 will always have remainder of zero. You can start i from 2 instead of 1 in your for if you want to skip 1.
I'd suggest something like this: (note this is based in part on BevynQ's answer below):
for(int i = 2; i <= num; i++){
while (num >= i && num % i == 0) {
System.out.println(i);
num /= i;
}
}

If statement and too much printing

I can't seem to figure out what is wrong here. In the third scenario if (i == n && i % 2 == 0), I only want it to print out 16 once (as given in the main method). But for some odd reason it prints it out 3 times. Can somebody explain why???
public class Foursix {
public static void main(String[] args) {
printEven(1,7);
printEven(21,2);
printEven(16,16);
//main
}
public static void printEven(int i, int n) {
System.out.print("[ ");
//n is greater than i
if (i <= n) {
for (int t = i; t <= n; t++) {
if (t % 2 == 0) {
System.out.print(t + " ");
//if statement inner
}
//for loop
}
//if statement outer
}
//i is greater than n
if (i >= n) {
for (int t = i; t >= n; t--) {
if (t % 2 == 0) {
System.out.print(t + " ");
//if statement inner
}
//for loop
}
//if statement outer
}
//i is the same as n
if (i == n && i % 2 == 0) {
System.out.print(i);
//if statement
}
System.out.print("]");
System.out.println();
//printEven
}
//class
}
You're passing in 16,16, so all three of your if() conditions are TRUE:
if (i <= n) { 16 <= 16 -> TRUE
if (i >= n) { 16 >= 16 -> TRUE
if (i == n && i % 2 == 0) { 16 == 16 && 16 % 2 -> TRUE
Given that you're explicitly testing for all three of greater than/less than/equal, you probably want these:
if (i < n) { ... }
else if (i > n) { ... }
else if (i % 2 == 0) { ... }

Writing A Recursive Function That Counts Zeros

It is possible to count the number of zeros in an integer through a recursive method that takes a single int parameter and returns the number of zeros the parameter has.
So:
zeroCount(1000)
Would Return:
3
You can remove the last digit from an integer by doing: "12345 / 10" = 1234
You can get the last digit from an integer by doing: "12345 % 10" = 5
This is what I have so far:
public static int zeroCount(int num)
{
if(num % 10 == 0)
return num;
else
return zeroCount(num / 10);
}
Does anyone have any suggestions or ideas for helping me solve this function?
public static int zeroCount(int num)
{
if(num == 0)
return 0;
if(num %10 ==0)
return 1 + zeroCount(num / 10);
else
return zeroCount(num/10);
}
this would work
Run through your code in your head:
zeroCount(1000)
1000 % 10 == 0, so you're going to return 1000. That doesn't make sense.
Just pop off each digit and repeat:
It sounds like homework, so I'll leave the actual code to you, but it can be done as:
zeroes(0) = 1
zeroes(x) = ((x % 10 == 0) ? 1 : 0) + zeroes(x / 10)
Note that without the terminating condition, it can recurse forever.
There are three conditions here:
1. If number is single digit and 0 , then return 1
2. If number is less than 10 i.e. it is a number 1,2,3...9 then return 0
3. call recursion for zeros(number/10) + zeros(n%10)
zeros(number){
if(number == 0 ) //return 1
if(number < 10) //return 0
else
zeros(number/10) + zeros(number%10)
}
n/10 will give us the n-1 digits from left and n%10 gets us the single digit.
Hope this helps!
Check this out for positive integers:
public static int zeroCount(int number) {
if (number == 0) {
return 1;
} else if (number <= 9) {
return 0;
} else {
return ((number % 10 == 0) ? 1 : 0) + zeroCount(number / 10);
}
}
it is a simple problem and you don't need to go for recursion
I think a better way would be converting the integer to a string and check for char '0'
public static int zeroCount(int num)
{
String s=Integer.toString(num);
int count=0;
int i=0;
for(i=0;i<s.length;i++)
{
if(s.charAt(i)=='0')
{
count++;
}
}
return count;
}
You have to invoke your recursive function from both if and else. Also, you were missing a Base Case: -
public static int zeroCount(int num)
{
if(num % 10 == 0)
return 1 + zeroCount(num / 10);
else if (num / 10 == 0)
return 0;
else
return zeroCount(num / 10);
}
import java.util.*;
public class Count
{
static int count=0;
static int zeroCount(int num)
{
if (num == 0){
return 1;
}
else if(Math.abs(num) <= 9)
{
return 0;
}
else
{
if (num % 10 == 0)
{ // if the num last digit is zero
count++;
zeroCount(num/10);
} // count the zero, take num last digit out
else if (num%10 !=0){
zeroCount(num/10);
}
}
return count;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Input: ");
int num = sc.nextInt();
System.out.println("Output: " +zeroCount(num));
}
}
public static int count_zeros(int n)
{
if(n<=9)
{
if(n==0)
{
return 1;
}
else
{
return 0;
}
}
int s=n%10;
int count=0;
if(s==0)
{
count=1;
}
return count+count_zeros(n/10);
}
int countZeros(int n){
//We are taking care of base case
if(n<=9){
if(n==0){
return 1;
}
else
{
return 0;
}
}
int last=n%10; //last element of number for e.g- 20403, then last will give 3
int count=0; //Initalsizing count as zero
if(last==0){ //We are checking either the last digit is zero or not if it will
will update count from 0 to 1
count=1;
}
return count+countZeros(n/10); //Recursive call
}
int check(int n){
if(n==0)
return 1;
return 0;
}
int fun(int n)
{
if(n/10==0)
{
if(n==0){
return 1;
}
else{
return 0;
}
}
return check(n%10)+fun(n/10);
}
Check this out, this is the solution I came up with.
int countZeros(int input){
//base case
if(input == 0){
return 1;
}
int count = 0;
int lastDigit = input%10;
if(lastDigit == 0){
count = 1;
}
//calc the smallInput for recursion
int smallInput = input/10;
//set smallAns = 0, if i/p itself is not 0 and no 0 is present then return smallAns = 0
int smallAns = 0;
//recursion call
if(smallInput != 0){
smallAns = countZerosRec(smallInput);
}
//if we get lastDigit = 0 then return smallAns + 1 or smallAns + count, else return smallAns
if(lastDigit == 0){
return smallAns+count;
}
else{
return smallAns;
}}
You know that x % 10 gives you the last digit of x, so you can use that to identify the zeros. Furthermore, after checking if a particular digit is zero you want to take that digit out, how? divide by 10.
public static int zeroCount(int num)
{
if(num == 0) return 1;
else if(Math.abs(num) < 9) return 0;
else return (num % 10 == 0) ? 1 + zeroCount(num/10) : zeroCount(num/10);
}
I use math.Abs to allow negative numbers, you have to import java.lang.Math;
static int cnt=0;
public static int countZerosRec(int input) {
// Write your code here
if (input == 0) {
return 1;
}
if (input % 10 == 0) {
cnt++;
}
countZerosRec(input / 10);
return cnt;
}
CPP Code using recursion:
int final=0;
int countZeros(int n)
{
if(n==0) //base case
return 1;
int firstn=n/10;
int last=n%10;
int smallop=countZeros(firstn);
if(last==0)
final=smallop+1;
return final;
}
int countZeros(int n)
{
if(n==0)
{
return 1;
}
if(n<10) // Needs to be java.lang.Math.abs(n)<10 instead of n<10 to support negative int values
{
return 0;
}
int ans = countZeros(n/10);
if(n%10 == 0)
{
ans++;
}
return ans;
}
public static int countZerosRec(int input){
// Write your code here
if(input == 0)
return 1;
if(input <= 9)
return 0;
if(input%10 == 0)
return 1 + countZerosRec(input/10);
return countZerosRec(input/10);
}

Categories

Resources