I write the following code that will read a line, convert them into integer and count how many even, odd, and zero digits in a line.
But the problem is that, whenever I enter zero, it will make calculation on the countEven in my code, rather than countZero.
What's wrong with my code?
I don't have any problem on count even digits and odd digits in my code, it's just zeros.
Scanner stdin = new Scanner(System.in);
String str = "";
int countOdd = 0, countEven = 0, countZero = 0;
str = stdin.nextLine();
char[] breakDown = str.toCharArray();
Integer convertInt;
for (int i = 0; i < breakDown.length; i++) {
convertInt = new Integer(breakDown[i]);
if (convertInt % 2 == 1)
countOdd++;
if (convertInt % 2 == 0 && convertInt != 0)
countEven++;
if (convertInt == 0)
countZero++; }
When you cast the character '0' to an integer, it becomes 48, not 0. The expression breakDown[i] is of type char, but it is getting cast to int when you pass it to the Integer constructor.
You could just get rid of the conversion to Integer and write this inside your loop.
if (breakDown[i] % 2 == 1) {
countOdd++;
}
if (breakDown[i] % 2 == 0 && breakDown[i] != '0') {
countEven++;
}
if (breakDown[i] == '0') {
countZero++;
}
The Problem you have in your code is that new Integer(breakDown[i]) returns the value of the ASCII code and not the actual value of the digit. So it return 0x30, this is even and your code correctly increases countEven and not countZero.
First solution in my mind, use Integer.valueOf(breakDown[i]-0x30) instead.
Related
I'm trying to remove trailing zeroes from an integer and here is my code so far.
import java.math.BigInteger;
public class newuhu {
public static int numTrailingZeros(int s) {
BigInteger J = BigInteger.valueOf(s);
String sb = J.toString();
String Y = "";
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == '0') {
sb.replaceAll("0"," ");
}
return Integer.parseInt(Y);
}
Note: I turned my int into a Biginteger because I've been warned that some inputs may look like 20!, which is 2.432902e+18
However, my IntelliJ debugging tool tells me that variable sb isn't in the loop. So, I'm trying to understand what must be done to make sure sb is in the loop.
Please understand that I'm a beginner in Java so, I'm trying to learn something new.
replaceAll replaces all occurrences of string with character that you want (ie space) so you don't need loop at all, also you're concerned about overflow so you should actually use BigInteger as a parameter, not int (int wont fit anything close to 20!) but there's another issue with your code, you said you want to replace trailing zeros but right now you will replace every 0 with blank character, you should try to use something like https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
public class newuhu {
public static int numTrailingZeros(BigInteger s) {
String sb = s.toString();
return Integer.parseInt(sb.replaceAll("0", "")); // consider returning something else if you're working with BigInteger
}
Keep in mind that when doing BigInteger.valueOf(int) does not have an effect as a number to big for int will never be stored in an int. Also 20! is fine for int.
public static String trimTrailingZeros(String source) {
for (int i = source.length() - 1; i > 0; ++i) {
char c = source.charAt(i);
if (c != '0') {
return source.substring(0, i + 1);
}
}
return ""; // or return "0";
}
Or if you prever BigInteger.
public static BigInteger trimTrailingZeros(BigInteger num) {
while (num.remainder(BigInteger.TEN).signum() == 0) {
num = num.divide(BigInteger.TEN);
}
return num;
}
This should be fast as you only create one string (via substring).
(First: variables and fields should start with a small letter - when no constants.)
It should be
sb = sb.replaceAll(...)
as sb is not changed by replaceAll, only the replaced value is returned. The class String gives immutable values, that always remain the same, so you can assign a variable to a variable and changing values of either variable will never influence the other - no further sharing.
Then it should be:
sb = sb.replaceFirst("0$", "");
replaceAll would replace every 0, like "23043500" to "23435".
replaceFirst replaces the _regular expression: char '0' at the end $.
Overflow on the input number is not possible, as you are already passing an int.
public static int numTrailingZeros(int n) {
while (n != 0 && n % 10 == 0) {
n /= 10;
}
return n;
}
public static int numTrailingZeros(String n) {
n = n.replaceAll("0+", "");
if (n.isEmpty() || n.equals("-")) { // "-0" for pessimists?
n = "0";
}
return Integer.parseInt(n);
}
% is the modulo operator, the remainder of an integer division 147 % 10 == 7.
The name is misleading, or you are calculating something different.
public static int numTrailingZeros(int n) {
int trailingZeros = 0;
while (n != 0 && n % 10 == 0) {
n /= 10;
++trailingZeros ;
}
return trailingZeros ;
}
The problem here is that sb.replaceAll("0","") won't do anything. You're throwing away the return value that contains your replaced string. See here.
What you probably want is something like this:
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == '0') {
sb = sb.replaceAll("0"," ");
I'm not sure you need a while loop, though. ReplaceAll will... replace all of the zeros with spaces.
I am trying to print every 3rd character of a string so an example would be:
123456 returns 36
But my code below returns 14
public String getEveryThird() {
String newString = "";
for (int i = 0; i < string.length(); i++) {
if (i % 3 == 0) {
newString += (string.charAt(i));
}
}
return newString;
}
Good try. The only problem is you choose the wrong remainder of the division since elements start from 0.
Try this condition:
if (i % 3 == 2)
Your current approach is off in the remainder (as already mentioned), however a much faster approach is available; instead of iterating every character, start with the third character and increase your index by three on each iteration. Remember, the third character is at index two (0, 1, 2). Also, it is better to use a StringBuilder over String concatenation (as Java String is immutable). Like,
StringBuilder sb = new StringBuilder();
for (int i = 2; i < string.length(); i += 3) {
sb.append(string.charAt(i));
}
return sb.toString();
It is returning 14 because your loop starts in 0 and 0 % 0 is equal to 0.
Then, when it gets to number 4, the index i is equal to 3, and again 3 % 3 = 0.
Try something like:
if((i+1) % 3 == 0){
newString += (string.charAt(i));
}
I want to create a loop where when you add a number, it gives you the equivalent character in that position in the alphabet. For example, a = 0, b = 1 etc..
I've already created that and it works, but the problem I have is that when it reaches 26, I would like it go back and continue the loop. For example, 25 is z, so 27 should be b.
Code:
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toLowerCase().toCharArray();
if (i < 0)
{
return null;
}
if(i > 25)
{
i = 0;
}
return Character.toString(alphabet[i]); //converts character to String and returns the character
}
You can use the modulo operation on i.
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toLowerCase().toCharArray();
int i =30;
System.out.println(alphabet[i % alphabet.length]);
You don't need any arrays or loops at all. Just do this:
return (char)('a' + (i % 26));
Try using a modulo operator for your indices. For example,
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toLowerCase().toCharArray();
if (i < 0) return;
i = i % 26;
return Character.toString(alphabet[i]);
Or
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toLowerCase().toCharArray();
if (i > 0)
return Character.toString(alphabet[i % 26]);
else
return;
I need to add two binary numbers and return the sum. No base conversions are allowed. I know the long method, using arrays. But is there anything shorter ? And by shorter I mean "having smaller code length". Thanks in advance.
In case I was not explicit enough, here is an example:
Input:
1101
11
Output: 10000
The sum of two (binary) integers a and b can be computed as a+b, because all arithmetic is done in binary.
If your input is in human readable strings rather than binary, you can compute their sum in binary using the standard BigInteger class:
import java.math.BigInteger;
String sum(String a, String b) {
return new BigInteger(a, 2).add(new BigInteger(b, 2)).toString(2);
}
Represent the binary numbers as two strings. Reverse the two strings. Then, you can iterate along both strings simultaneously, adding values to three arrays, two which represent the binary digit being added from the strings and the third to represent the carry digit. Create a fourth array representing the answer (you might have to find the limit for how long the answer can possibly be).
fill the answer array by using standard binary adding:
0 + 0 = 0 in the same position,
1 + 0 = 0 + 1 = 1 in the same position,
1 + 1 = 0 in the same position, and carry a 1 to the next position,
1 + 1 + 1 = 1 in the same position, and carry a 1 to the next position.
Reverse the array and you'll have the answer as a binary number.
Here are a couple options, not using any utility methods provided by Java. These don't account for sign (leading +/-) so they only handle whole numbers.
This first method converts the binary strings to integers, adds the integers, then converts the result back to binary. It uses a method-local inner class Convert to avoid duplicating the binaryToInt() code for each of the parameters.
static String binaryAdd1(String binary1, String binary2) {
class Convert {
int binaryToInt(String binary) {
int result = 0;
for (int i = 0; i < binary.length(); i++) {
char c = binary.charAt(i);
result *= 2;
if (c == '1') {
result++;
} else if (c != '0') {
throw new IllegalArgumentException(binary);
}
}
return result;
}
}
final Convert convert = new Convert();
int int1 = convert.binaryToInt(binary1);
int int2 = convert.binaryToInt(binary2);
String result = "";
int temp = int1 + int2;
do {
result = ((temp & 1) == 1 ? '1' : '0') + result;
temp >>= 1;
} while (temp > 0);
return result;
}
This second method uses binary addition logic, as specified by JHaps in his answer, to directly add together the two parameters. No intermediate conversion to integers here.
static String binaryAdd2(String binary1, String binary2) {
final String validDigits = "01";
String binarySum = "";
// pad the binary strings with one more significant digit for carrying
String bin1 = '0' + binary1;
String bin2 = '0' + binary2;
// add them together starting from least significant digit
int index1 = bin1.length() - 1;
int index2 = bin2.length() - 1;
boolean carry = false;
while (index1 >= 0 || index2 >= 0) {
char char1 = bin1.charAt(index1 >= 0 ? index1 : 0);
char char2 = bin2.charAt(index2 >= 0 ? index2 : 0);
if (validDigits.indexOf(char1) < 0)
throw new NumberFormatException(binary1);
if (validDigits.indexOf(char2) < 0)
throw new NumberFormatException(binary2);
if (char1 == char2) {
binarySum = (carry ? '1' : '0') + binarySum;
carry = char1 == '1';
} else {
binarySum = (carry ? '0' : '1') + binarySum;
}
index1--;
index2--;
}
if (binarySum.length() > 1 && binarySum.charAt(0) == '0') {
binarySum = binarySum.substring(1);
}
String result = binarySum.toString();
return result;
}
The title is pretty much self explanatory. :)
1232 => 0
1231030 => 1
2000 => 3
34444400000 => 5
If it fits into an int/long, just check if the number modulo 10 is 0 and keep a counter:
long x = ...
if (x == 0) {
return 0;
}
int counter = 0;
while (x % 10 == 0) {
counter++;
x /= 10;
}
If it's too big to fit in long, store it in a String and count zeroes from the last char:
String s = ...
int counter = 0;
while(counter < s.length() && s.charAt(s.length() - 1 - counter) == '0') {
counter++;
}
Integer class has an inbuilt function to count the trailing zeros.
javadocs
int trailingZeroes = Integer.numberOfTrailingZeros(int i);
Three lines:
int zeroes = 0
while(num%10 == 0 && num != 0) {
zeroes++;
num /= 10;
}
This uses the modulus operator. As long as we can divide by ten without remainder, increment the counter.
Here is another solution using Java 8 Streams:
int trailingZeros = String.valueOf(number).chars()
.reduce(0, (count, ch) -> (ch == '0') ? count + 1 : 0);
This transforms the number to an IntStream. This stream is then reduced using a lambda which resets a counter each time a non-zero char comes up.
You could always just use a regular expression:
Pattern pattern = Pattern.compile("(0+)$");
Matcher matcher = pattern.matcher(String.valueOf(123140000));
Integer trailingZeroes = 0;
if (matcher.find()) {
trailingZeroes = matcher.group(1).length();
}
System.out.println(trailingZeroes);
you can turn the int to a String and iterate in reverse, counting the zeros until you find a char that is not zero:
int countZeros(int x){
String a = Integer.toString(x);
int numOfZeros = 0;
for(int i = a.length() - 1; i >= 0; i--)
if (a.charAt(i) != '0') break;
else numOfZeros ++;
return numOfZeros;
}
Testing with :
System.out.println(countZeros(25000)); will print 3
System.out.println(countZeros(25)); will print 0
Hope this helps.
Not tried this code but this should work.
int counterForZeros=0;
for(long i=10;true;)
{
if(num%i==0)
{
counterForZeros++;
i*=10;
}
else
{
break;
}
}
System.out.println("Number of zeros in "+num+" is "+counterForZeros);
Well, if this is a contest to see who can do it in the fewest lines:
trailingZeroes = String.valueOf(num).length() - String.valueOf(num).replaceAll("0*$","").length();