Digit amount in an integer [duplicate] - java

This question already has answers here:
Way to get number of digits in an int?
(29 answers)
Closed 24 days ago.
How can I find the amount of digits in an integer? Mathematically, and by using functions if there are any.
I don't really know how to do that, since I'm a somewhat beginner.

Another option would be to do it iteratively by dividing number by 10, until result is 0.
int number = ...;
int count = 1;
while ((number /= 10) != 0) {
count++;
}

In this program we use a for loop without any body.
On each iteration, the value of num is divided by 10 and count is incremented by 1.
The for loop exits when num != 0 is false, i.e. num = 0.
Since, for loop doesn't have a body, you can change it to a single statement in Java as such:
for(; num != 0; num/=10, ++count);
public class Main {
public static void main(String[] args) {
int count = 0, num = 123456;
for (; num != 0; num /= 10, ++count) {
}
System.out.println("Number of digits: " + count);
}
}

There are many ways to calculate the number of digits in a number. The main difference between them is how important performance is to you. The first way is to translate a number into a string and then take its length:
public static int countDigitsFoo(int x) {
if (x == Integer.MIN_VALUE) {
throw new RuntimeException("Cannot invert Integer.MIN_VALUE");
}
if (x < 0) {
return countDigitsFoo(-x); // + 1; if you want count '-'
}
return Integer.toString(x).length();
}
This method is bad for everyone, except that it is easy to write. Here there is an extra allocation of memory, namely the translation of a number into a string. That with private calls to this function will hit performance very hard.
The second way. You can use integer division and sort of go by the number from right to left:
public static int countDigitsBoo(int x) {
if (x == Integer.MIN_VALUE) {
throw new RuntimeException("Cannot invert Integer.MIN_VALUE");
}
if (x < 0) {
return countDigitsBoo(-x); // + 1; if you want count '-'
}
int count = 0;
while (x > 0) {
count++;
x /= 10;
}
return count;
}
but even this method can be improved. I will not write it in full, but I will give part of the code.
P.S. never use this method, it is rather another way to solve this problem, but no more
public static int countDigitsHoo(int x) {
if (x == Integer.MIN_VALUE) {
throw new RuntimeException("Cannot invert Integer.MIN_VALUE");
}
if (x < 0) {
return countDigitsHoo(-x); // + 1; if you want count '-'
}
if (x < 10) {
return 1;
}
if (x < 100) {
return 2;
}
if (x < 1000) {
return 3;
}
// ...
return 10;
}
You also need to decide what is the number of digits in the number. Should I count the minus sign along with this? Also, in addition, you need to add a condition on Integer.MIN_VALUE because
Integer.MIN_VALUE == -Integer.MIN_VALUE
This is due to the fact that taking a unary minus occurs by -x = ~x + 1 at the hardware level, which leads to "looping" on -Integer.MIN_VALUE

In Java, I would convert the integer to a string using the .toString() function and then use the string to determine the number of digits.
Integer digit = 10000;
Integer digitLength = abs(digit).toString().length();

Related

Program to sum the odd digits recursively

Using recursion, If n is 123, the code should return 4 (i.e. 1+3). But instead it is returning the last digit, in this case 3.
public static int sumOfOddDigits(NaturalNumber n) {
int ans = 0;
if (!n.isZero()) {
int r = n.divideBy10();
sumOfOddDigits(n);
if (r % 2 != 0) {
ans = ans + r;
}
n.multiplyBy10(r);
}
return ans;
}
It isn't clear what NaturalNumber is or why you would prefer it to int, but your algorithm is easy enough to follow with int (and off). First, you want the remainder (or modulus) of division by 10. That is the far right digit. Determine if it is odd. If it is add it to the answer, and then when you recurse divide by 10 and make sure to add the result to the answer. Like,
public static int sumOfOddDigits(int n) {
int ans = 0;
if (n != 0) {
int r = n % 10;
if (r % 2 != 0) {
ans += r;
}
ans += sumOfOddDigits(n / 10);
}
return ans;
}
One problem is that you’re calling multiplyBy on n and not doing anything with the result. NaturalNumber seems likely to be immutable, so the method call has no effect.
But using recursion lets you write declarative code, this kind of imperative logic isn’t needed. instead of mutating local variables you can use the argument list to hold the values to be used in the next iteration:
public static int sumOfOddDigits(final int n) {
return sumOfOddDigits(n, 0);
}
// overload to pass in running total as an argument
public static int sumOfOddDigits(final int n, final int total) {
// base case: no digits left
if (n == 0)
return total;
// n is even: check other digits of n
if (n % 2 == 0)
return sumOfOddDigits(n / 10, total);
// n is odd: add last digit to total,
// then check other digits of n
return sumOfOddDigits(n / 10, n % 10 + total);
}

Java: fast way to check if digits in int are in ascending order

I'm writing a program that finds all of the Armstrong numbers in a range between zero and Integer.MAX_VALUE. Time limit is 10 seconds. I've found that the most time-consuming method is the one that narrows the range of numbers to process by picking only those having their digits in ascending order (with trailing zeros if any). It takes about 57 seconds to run on my machine. Is there any way to make it faster?
static boolean isOK(int x)
{
int prev = 0;
while(x > 0)
{
int digit = x % 10;
if((digit > prev || digit == 0) && prev != 0) return false;
x /= 10;
prev = digit;
}
return true;
}
This method reduces the number of numbers to process from 2.147.483.647 to 140.990.
Perhaps instead of sifting through all the ints, just build up the set of numbers with digits in ascending order. I would argue that you probably want a set of strings (and not ints) because it it is easier to build (recursively by appending/ prepending characters) and then later on you need only the individual "digits" for the power test.
My take on the problem, goes to Long.MAX_VALUE (19 digits) in about 6 seconds and all the way to 39 digits in about an hour
One alternative is to construct the set of Armstrong numbers one by one and count them instead of checking every number to see whether it's an Armstrong number or not.
In constructing the whole set, note that when you choose each digit, the set of digits you can choose for the next position is determined, and so on. Two alternatives to implement such a method are recursion and backtracking (which is basically a cheaper way to implement recursion).
This method will not need the use of time-consuming division and remainder operations.
There is very little optimisable code here. It is likely that your time issue is elsewhere. However, one technique comes to mind and that is Memoization.
static Set<Integer> oks = new HashSet<>();
static boolean isOK(int x) {
if (!oks.contains(x)) {
int prev = 0;
while (x > 0) {
int digit = x % 10;
if ((digit > prev || digit == 0) && prev != 0) {
return false;
}
x /= 10;
prev = digit;
}
// This one is OK.
oks.add(x);
}
return true;
}
This trick uses a Set to remember all of the ok numbers so you don't need to check them. You could also keep a Set of those that failed too to avoid checking them again but keeping all integers in a collection is likely to break something.
You perform two divisions. Divisions are slower than multiplications. So is there a way to change a division into a multiplication? Well... yes, there is.
public static boolean isArmstrongNumber(int n) {
int prev = 0;
while (n > 0) {
int quotient = n / 10;
int digit = n - (quotient * 10);
if ((digit > prev || digit == 0) && prev != 0) {
return false;
}
n = quotient;
prev = digit;
}
return true;
}
The following code doesn't deal with trailing zeroes but is worth checking if it looks promising in terms of performance.
static boolean isOK(int x) {
if (x < 10) {
return true;
}
String xs = Integer.toString(x);
for (int i = 1; i < xs.length(); i++) {
if (xs.charAt(i) < xs.charAt(i - 1)) {
return false;
}
}
return true;
}
The following code runs x4 as fast as the original (3 sec. on my laptop) and prints 140990 in 3 sec.
The method isOK is unchanged
public class Main {
public static boolean isOK(int x) {
int prev = 0;
while (x > 0) {
int digit = x % 10;
if (prev != 0 && (digit > prev || digit == 0)) return false;
x /= 10;
prev = digit;
}
return true;
}
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
Set<Integer> candidates = IntStream.range(0, Integer.MAX_VALUE)
.parallel()
.filter(n -> isOK(n))
.boxed()
.collect(Collectors.toSet());
long stop = System.currentTimeMillis() - start;
System.err.printf("%d in %d sec.", candidates.size(), stop / 1000);
}
}
It has been asked on the MIU test, unfortunately, I was not able to solve it, I later worked on it and it worked fine.
static int isAscending(int n){
int rem, rem1, pval = 0; boolean isAsc = true;
while(n != 0){
rem = n % 10;
n /= 10;
rem1 = n % 10;
n /= 10;
if(rem > rem1){
continue;
} else {
isAsc = false;
break;
}
}
if(isAsc == true){
return 1;
} else {
return 0;
}
}

All digits in int are divisible by certain int

I am trying to figure out how to count all numbers between two ints(a and b), where all of the digits are divisible with another int(k) and 0 counts as divisible.Here is what I've made so far, but it is looping forever.
for (int i = a; i<=b; i++){
while (i < 10) {
digit = i % 10;
if(digit % k == 0 || digit == 0){
count ++;
}
i = i / 10;
}
}
Also I was thinking about comparing if all of the digits were divisible by counting them and comparing with number of digits int length = (int)Math.Log10(Math.Abs(number)) + 1;
Any help would be appreciated. Thank you!
Once you get in to your while block you're never going to get out of it. The while condition is when i less than 10. You're dividing i by 10 at the end of the whole block. i will never have a chance of getting above 10.
Try this one
public class Calculator {
public static void main(String[] args) {
int a = 2;
int b = 150;
int k = 3;
int count = 0;
for (int i = a; i <= b; i++) {
boolean isDivisible = true;
int num = i;
while (num != 0) {
int digit = num % 10;
if (digit % k != 0) {
isDivisible = false;
break;
}
num /= 10;
}
if (isDivisible) {
count++;
System.out.println(i+" is one such number.");
}
}
System.out.println("Total " + count + " numbers are divisible by " + k);
}
}
Ok, so there are quite a few things going on here, so we'll take this a piece at a time.
for (int i = a; i <= b; i++){
// This line is part of the biggest problem. This will cause the
// loop to skip entirely when you start with a >= 10. I'm assuming
// this is not the case, as you are seeing an infinite loop - which
// will happen when a < 10, for reasons I'll show below.
while (i < 10) {
digit = i % 10;
if(digit % k == 0 || digit == 0){
count ++;
// A missing line here will cause you to get incorrect
// results. You don't terminate the loop, so what you are
// actually counting is every digit that is divisible by k
// in every number between a and b.
}
// This is the other part of the biggest problem. This line
// causes the infinite loop because you are modifying the
// variable you are using as the loop counter. Mutable state is
// tricky like that.
i = i / 10;
}
}
It's possible to re-write this with minimal changes, but there are some improvements you can make that will provide a more readable result. This code is untested, but does compile, and should get you most of the way there.
// Extracting this out into a function is often a good idea.
private int countOfNumbersWithAllDigitsDivisibleByN(final int modBy, final int start, final int end) {
int count = 0;
// I prefer += to ++, as each statement should do only one thing,
// it's easier to reason about
for (int i = start; i <= end; i += 1) {
// Pulling this into a separate function prevents leaking
// state, which was the bulk of the issue in the original.
// Ternary if adds 1 or 0, depending on the result of the
// method call. When the methods are named sensibly, I find
// this can be more readable than a regular if construct.
count += ifAllDigitsDivisibleByN(modBy, i) ? 1 : 0;
}
return count;
}
private boolean ifAllDigitsDivisibleByN(final int modBy, final int i) {
// For smaller numbers, this won't make much of a difference, but
// in principle, there's no real reason to check every instance of
// a particular digit.
for(Integer digit : uniqueDigitsInN(i)) {
if ( !isDigitDivisibleBy(modBy, digit) ) {
return false;
}
}
return true;
}
// The switch to Integer is to avoid Java's auto-boxing, which
// can get expensive inside of a tight loop.
private boolean isDigitDivisibleBy(final Integer modBy, final Integer digit) {
// Always include parens to group sub-expressions, forgetting the
// precedence rules between && and || is a good way to introduce
// bugs.
return digit == 0 || (digit % modBy == 0);
}
private Set<Integer> uniqueDigitsInN(final int number) {
// Sets are an easy and efficient way to cull duplicates.
Set<Integer> digitsInN = new HashSet<>();
for (int n = number; n != 0; n /= 10) {
digitsInN.add(n % 10);
}
return digitsInN;
}

Boolean in Java

Prompt: You can test to see if an integer, x, is even or odd using the Boolean expression (x / 2) * 2 == x. Integers that are even make this expression true, and odd integers make the expression false. Use a for loop to iterate five times. In each iteration, request an integer from the user. Print each integer the user types, and whether it is even or odd. Keep up with the number of even and odd integers the user types, and print “Done” when finished, so the user won’t try to type another integer. Finally, print out the number of even and odd integers that were entered.
Here is the code I have so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer.");
int x = in.nextInt();
boolean even;
for (int i = 0; i == 5; i++) {
if ((x / 2) * 2 == x) {
even = true;
System.out.println(x + " is even.");
}
if ((x / 2) * 2 != x) {
even = false;
System.out.println(x + " is odd.");
}
}
}
Not looking for a solution, just some help as to what I need to do. Really confused about the whole Boolean thing.
This seems to be like your homework.
Seems like your 'boolean even' is not even being used, I would suggest that you don't declare nor use it. Use x = x%2 to get the number if it is even or odd is better. If it is even x should be 0, if it is odd x should be 1. % is equivalent to MOD
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
int even = 0; // keep tracks the number of even
int odd = 0; // keep tracks the number of odd
for (int i = 0; i < 5; i++) {
System.out.println("Enter an integer.");
x = in.nextInt();
if (x % 2 == 0) {
even++;
System.out.println(x + " is even.");
}
if (x % 2 == 1) {
odd++;
System.out.println(x + " is odd.");
}
}
System.out.println("Done");
System.out.println("Evens: " + even "\nOdds: " + odd);
}
This code should be the answer for your homework requirement. Your in.nextInt() should be inside the for loop since you need to request the user 5 times. Not only that, your loop should be < 5 as it will loop 5 times from 0, 1, 2, 3, 4
Well, your loop won't fire; i == 5 is always going to be false every time you reach the loop.
What you may want to change your loop statement to be would be:
for (int i = 0; i <= 5; i++) {
// code
}
Further, by virtue of the way Java evaluates branches, the variable even may not have been initialized. You need to instantiate it with a value.
boolean even = false;
Finally, the most straightforward way to tell if a number is even is to use the modulus operator. If it's divisible by two, it's even. Otherwise, it's odd.
if (x % 2 == 0) {
// even, do logic
} else {
// odd, do logic
}
You are missing a requirement from the assignment - that is, the ability to keep a running tally of the number of odd and even numbers, but I leave that as an exercise to the reader.
The part that you're missing is keeping track of how many even and how many odd numbers have been encountered. You'll want two separate int variables for this, which you'll declare before your main loop.
int numEvens = 0;
int numOdds = 0;
Then, in the branches where you work out whether the entered number is odd or even, you'll increment one or other of these numbers.
Lastly, at the end of your program, you can print them both out in a message.
if you want to do this with java boolean..i think this might help you
package stackOverFlow;
public class EvenOddNumber {
public boolean findEvenOdd(int num) {
if (num % 2 == 0) {
return true;
}
else {
return false;
}
}
}
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int num;
EvenOddNumber e = new EvenOddNumber();
System.out.print("Enter a number:");
Scanner scan = new Scanner(System.in);
num = scan.nextInt();
System.out.println( num+" is even number?: " + e.findEvenOdd(num));
}
}
A simpler way to find even and odd values is to divide number by 2 and check the remainder:
if(x % 2 == 0) // remainder is 0 when divided by 2
{
//even num
}
else
{
//odd num
}

Method to check if number is symmetric in Java [duplicate]

This question already has answers here:
How do I check if a number is a palindrome?
(53 answers)
Closed 9 years ago.
I need help with a method to check if a number is symmetric, so from what I understand I need to check equality between all the numbers and to make sure there is no different number amounts them...right?
This is my code:
public boolean isSemetric (int number) {
int temp;
boolean answer = true;
while (number != 0) {
temp = number % 10;
number /= 10;
if (temp != (number%10)) {
answer = false;
} else {
answer = true;
}
}
return answer;
}
I'm kind of new to programming so be forgiven to my code :/
Thanks!
As peter.petrov pointed out in the comment section of your question, your method as it's written will always return false, except for when number is equal to 0. The reason for this can be seen when you pass in a number like 111 and step through the code in a debugger. The final iteration will fail because number /= 10 will result in 0, and temp will be 1, which fails your test.
If you are indeed looking to identify palindromes, consider the following approach that should be simple to implement
1. copy number into temp
2. convert temp to a String, and reverse it (tmpStr)
3. convert tmpStr back to an integer (reversedInt)
4. compare number and reversedInt for equality
viola. Not the most efficient algorithm, but its easy to understand and gets the job done.
I would do it like this (I don't want to use String here and I don't want to use local array variable for the digits).
public static boolean isSymmetric (long number) {
if (number == 0) return true;
else if (number < 0) return false;
long DEG_10 = (long)(Math.pow(10, (int)Math.log10(number)));
while (number > 0){
long dStart = number / DEG_10;
long dEnd = number % 10;
if (dStart != dEnd) return false;
number = (number - dStart * DEG_10 - dEnd) / 10;
DEG_10 /= 100;
}
return true;
}
This is the easiest approach I can think of - Get the String value of the number, if the reverse is the same then it is symmetrical.
// Symmetry
public static boolean isSymmetric(int number) {
String val = String.valueOf(number); // Get the string.
StringBuilder sb = new StringBuilder(val);
return (val.equals(sb.reverse().toString())); // if the reverse is the same...
}
Here's a somewhat fixed up version of your code. However, it checks if all numbers are the same, e.g. 5555 or 111. 11211 would return false.
public boolean areAllDigitsTheSame (int number) {
int temp;
boolean answer = true;
while (number >= 10) {
temp = number % 10;
number /= 10;
if (temp != (number%10)) {
return false
}
}
return true;
}
Edit: The C++ answer in the linked question works by constructing the reverse number gradually in the loop, and finally checking if they're the same. This is a similar to what you are doing.
Here's another version for fun:
public boolean isPalindrome (int number) {
int reversedNumber = 0;
while (number > 0) {
int digit = number % 10;
reversedNumber = reversedNumber*10 + digit;
if (reversedNumber == number) { // odd number of digits
return true;
}
number /= 10;
if (reversedNumber == number) { // even number of digits
return true;
}
}
return false;
}

Categories

Resources