Given an integer, how could you check if it contains a 0, using Java?
1 = Good
2 = Good
...
9 = Good
10 = BAD!
101 = BAD!
1026 = BAD!
1111 = Good
How can this be done?
Do you mean if the decimal representation contains a 0? The absolute simplest way of doing that is:
if (String.valueOf(x).contains("0"))
Don't forget that a number doesn't "inherently" contain a 0 or not (except for zero itself, of course) - it depends on the base. So "10" in decimal is "A" in hex, and "10" in hex is "16" in decimal... in both cases the result would change.
There may be more efficient ways of testing for the presence of a zero in the decimal representation of an integer, but they're likely to be considerably more involved that the expression above.
If for some reason you don't like the solution that converts to a String you can try:
boolean containsZero(int num) {
if(num == 0)
return true;
if(num < 0)
num = -num;
while(num > 0) {
if(num % 10 == 0)
return true;
num /= 10;
}
return false;
}
This is also assuming num is base 10.
Edit: added conditions to deal with negative numbers and 0 itself.
You can convert it to a string and check if it contains the char "0".
int number = 101;
if( ( "" + number ).contains( "0" ) ) {
System.out.println( "contains the digit 0" );
}
Integer.toString(yourIntValue).contains("0");
Here is a routine that will work detect zeros in integers. To make it work with any representation (decimal, hex, octal, binary), you need to pass in the base as a parameter.
public static boolean hasZero(int num, int base) {
assert base > 0 : "must have positive non-zero base";
if (num == 0)
return true;
while(num != 0) {
if (num % base == 0) {
return true;
}
else {
num = num / base;
}
}
return false;
}
public static void main(String args[]) {
System.out.println(hasZero(10, 10)); // true (base 10 int)
System.out.println(hasZero(-12, 10)); // false (base 10 int)
System.out.println(hasZero(0x10, 16)); // true (hex is base 16)
System.out.println(hasZero(0x1A, 16)); // false (hex is base 16)
}
I don't know if this is easier but here is another way.
Split the number into an array of ints. Then sort and check if the first element is zero.
E.g
int n = 14501;
// after splitting
int na = {1, 4, 5, 0, 1};
// after sorting
int na = {0, 1, 1, 4, 5};
Not using Java, but it's not exactly hard to convert from C++
PS. Shame on anyone using string conversion.
bool Contains0InBase10( unsigned int i, unsigned int& next )
{
unsigned int divisor = 10;
unsigned int remainder = 0;
while( divisor <= i )
{
unsigned int newRemainder = i%divisor;
if( newRemainder - remainder == 0)
{
// give back information allowing a program to skip closer to the next
// number that doesn't contain 0
next = i + (divisor / 10) - remainder;
return true;
}
divisor *= 10;
remainder = newRemainder;
}
return false;
}
Related
I was trying to solve 7.Reverse Integer on leetcode https://leetcode.com/problems/reverse-integer/.
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.
Example 1:
Input: x = 123
Output: 321
My solution for the above problem is
class Solution {
public int reverse(int x) {
int num=0;
if(x>Integer.MAX_VALUE||x<Integer.MIN_VALUE) return 0;
while(x!=0){
int a=x%10;
num=num*10+a;
x=x/10;
}
return num;
}
}
I'm getting 4 test cases wrong. One of which is :
Example
Input: 1534236469
Output : 1056389759
Expected: 0
Your problem is that the overflow is in the num variable and you are not checking for that. By adding a check to make sure the calculation will not overflow before performing num = num*10+a, you can return 0 when necessary.
Also, you weren't handling negative numbers properly. A check for a negative up front can allow you to work with a positive number and then just negate the result.
class Solution {
public int reverse(int x) {
int num=0;
Boolean negative = false;
if (x < 0) {
x = -x;
negative = true;
}
while(x!=0){
int a=x%10;
// Check if the next operation is going to cause an overflow
// and return 0 if it does
if (num > (Integer.MAX_VALUE-a)/10) return 0;
num=num*10+a;
x=x/10;
}
return negative ? -num : num;
}
}
The approach you've chosen is not that far off.
You currently check the input x to be in range of unsigned integer. But they ask to check x-reversed instead.
You aggregate your answer in an integer, hence you might overflow unnoticed.
Both of your problems can be solved if you aggregate your result num in an variable of type long instead and reject/zero the answer if after reversing it is out of bounds of unsigned int.
Alternative you can use Math.addExact(a, b), Math.multiplyExact(a,b) and a try-catch to exit immediately upon overflow.
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 2
class Solution {
public:
int reverse(int x) {
int rev = 0;
constexpr int top_limit = INT_MAX/10;
constexpr int bottom_limit = INT_MIN/10;
while (x) {
if (rev > top_limit || rev < bottom_limit)
return 0;
rev = rev * 10 + x % 10;
x /= 10;
}
return rev;
}
};
You're not dealing with the theoretical signed 32-bit integer overflow that might occur in the loop, meaning you'll sometimes return a number outside of that range. Also, the logic will not work as expected with negative values.
And to be really precise on the restriction of signed 32-bit, special care needs to be taken when the input is -231, as its absolute value does not represent a valid signed 32-bit integer.
class Solution {
public int reverse(int x) {
if (x < 0) return x == -2147483648 ? 0 : -reverse(-x);
int res = 0;
while (x > 0 && res < 214748364) {
res = res * 10 + x % 10;
x /= 10;
}
return x == 0 ? res
: res > 214748364 || x > 7 ? 0
: res * 10 + x;
}
}
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.
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 need a function in Java to give me number of bytes needed to represent a given integer. When I pass 2 it should return 1, 400 -> 2, 822222 -> 3, etc.
#Edit: For now I'm stuck with this:
numOfBytes = Integer.highestOneBit(integer) / 8
Don't know exactly what highestOneBit() does, but have also tried this:
numOfBytes = (int) (Math.floor(Math.log(integer)) + 1);
Which I found on some website.
static int byteSize(long x) {
if (x < 0) throw new IllegalArgumentException();
int s = 1;
while (s < 8 && x >= (1L << (s * 8))) s++;
return s;
}
Integer.highestOneBit(arg) returns only the highest set bit, in the original place. For example, Integer.highestOneBit(12) is 8, not 3. So you probably want to use Integer.numberOfTrailingZeros(Integer.highestOneBit(12)), which does return 3. Here is the Integer API
Some sample code:
numOfBytes = (Integer.numberOfTrailingZeroes(Integer.highestOneBit(integer)) + 8) / 8;
The + 8 is for proper rounding.
The lazy/inefficient way to do this is with Integer#toBinaryString. It will remove all leading zeros from positive numbers for you, all you have to do is call String#length and divide by 8.
Think about how to solve the same problem using normal decimal numbers. Then apply the same principle to binary / byte representation i.e. use 256 where you would use 10 for decimal numbers.
static int byteSize(long number, int bitsPerByte) {
int maxNumberSaveByBitsPerByte = // get max number can be saved by bits in value bitsPerByte
int returnValue = getFloor(number/maxNumberSaveByBitsPerByte); // use Math lib
if(number % maxNumberSaveByBitsPerByte != 0)
returnValue++;
return returnValue;
}
For positive values: 0 and 1 need 1 digit, with 2 digits you get the doubled max value, and for every digit it is 2 times that value. So a recursive solution is to divide:
public static int binaryLength (long l) {
if (l < 2) return 1;
else 1 + binaryLength (l /2L);
}
but shifting works too:
public static int binaryLength (long l) {
if (l < 2) return 1;
else 1 + binaryLength (l >> 1);
}
Negative values have a leading 1, so it doesn't make much sense for the question. If we assume binary1 is decimal1, binary1 can't be -1. But what shall it be? b11? That is 3.
Why you wouldn't do something simple like this:
private static int byteSize(int val) {
int size = 0;
while (val > 0) {
val = val >> 8;
size++;
}
return size;
}
int numOfBytes = (Integer.SIZE >> 3) - (Integer.numberOfLeadingZeros(n) >> 3);
This implementation is compact enough while performance-friendly, since it doesn't involve any floating point operation nor any loop.
It is derived from the form:
int numOfBytes = Math.ceil((Integer.SIZE - Integer.numberOfLeadingZeros(n)) / Byte.SIZE);
The magic number 3 in the optimized form comes from the assumption: Byte.SIZE equals 8
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));