This question already has answers here:
How do I find the sum of all odd digits of user input numeric string?
(5 answers)
Closed 2 years ago.
How to compute the sum of all 'odd digits of an input' using 'loop'. (For example, if the input is 32677, the sum would be 3 + 7 + 7 = 17.)
I can't quite figure out how to do that, can someone please help me out. This is what I have done so far, I don't know how to complete it or whether I have its right or wrong.
Any help would be appreciated!
System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();
int sum = 0;
int digits = 0;
for (int i = 0; i < length; i++) {
if (length % 2 == 1) {
digits += i;
sum = digits++;
}
}
System.out.println(sum);
Here comes a Java8-based solution:
final int result = input.chars()//make a stream of chars from string
.mapToObj(String::valueOf) // make every character a String to be able to use parseInt later
.mapToInt(Integer::parseInt) // transform character in int
.filter(i -> i % 2 == 1) // filter out even numbers
.sum();
You don't need to use String if your input is not so long.
also for safe side use long datatype.
Here is the working code with comments (explain each step).
long sumOddDigits(long value){
long temp = value; // copy in temp variable
long sum = 0;
while(temp > 0){
int digit = temp%10; // get last digit of number. example: 227 gives 7.
temp = temp / 10; // remove that last digit from number.227 will be 22.
if(digit % 2 == 1){
sum += digit;
}
}
return sum;
}
Your interpretation of the digits inside of input is not working this way.
System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();
int sum = 0;
for (int i = 0; i < length; i++) {
int digit = input.charAt(i) - '0';
if (digit % 2 == 1) {
System.out.println("Add digit: " + digit);
sum += digit;
}
}
System.out.println(sum);
In your loop, use Integer.parseInt(input.charAt(i)) to get the number at position i.
if(length%2==1){ that doesn't make sense here. You want to check if your number is odd, not the length of your string.
Related
Given an input string of digits, split that into groups of prime numbers by maintaining the order given in the input string and each group should hold all the characters of the input string. Find the count of such groups.
Example:
11375
Ans:
3
Explanation:
The 3 combinations are [11,37,5], [11,3,7,5] and [113,7,5]
Code that I tried
public int countPossibilities(String s) {
int n = s.length();
int[] ar = new int[n + 1];
ar[0] = 1;
for (int i = 1; i < n; i++) {
int j = i - 1;
while (j >= 0 && j >= i - 3) {
if (prime(s.substring(j, i)))
ar[i] += ar[j];
j--;
}
}
return ar[n];
}
public boolean prime(String s) {
int n = Integer.parseInt(s);
if (n < 2) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
This works fine if the input string length is small.
But the length of the input string can be from 1 to 10^5. So my program fails for large strings.
Example:
1350297079989171477791892123929141605573631151125933376097791877830238462471373933362476484818693477173990672289892448124097556197582379957168911392680312103962394732707409889862447273901522659
Expected result is : 4386816
What is the right approach to solve this problem.
Here's working Python code that answers your long example.
Let dp[i] represent the number of valid combinations ending at the ith index of the input. Then for each prime suffix of length x ending at input[i], we add to dp[i] the count of valid combinations ending at dp[i-x], provided there is also a count of valid combinations recorded for dp[i-x].
# https://rosettacode.org/wiki/Sieve_of_Eratosthenes
def primes2(limit):
if limit < 2: return []
if limit < 3: return [2]
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [False] * ((lmtbf - s) // p + 1)
return set(["2"] + [str(i + i + 3) for i, v in enumerate(buf) if v])
def f(n):
# The constant, k, limits the number
# of digits in the suffix we're
# checking for primality.
k = 6
primes = primes2(10**k)
dp = [0] * len(n) + [1]
for i in range(len(n)):
suffix = ""
for j in range(min(i + 1, k)):
suffix = n[i-j] + suffix
if suffix in primes and dp[i-j-1] > 0:
dp[i] += dp[i-j-1]
return dp[len(n) - 1]
Output:
n = "1350297079989171477791892123929141605573631151125933376097791877830238462471373933362476484818693477173990672289892448124097556197582379957168911392680312103962394732707409889862447273901522659"
print(f(n)) # 4386816
Proof of concept from my comments, but in C# (I'm an AP Comp Sci teacher that doesn't like to code in Java; go figure!):
Take the length of the input string minus 1 and call this "padLength".
Now raise 2 to the power of padLength to get the total number of
possibilities for string combinations; call this number
"numberOfCombinations". Next, count from 0 to numberOfCombinations and
convert that decimal number to a BINARY number, left padded with
zeroes out to padLength, called "binaryNumber". The binary number
represents whether or not a space should be added in-between the
digits of the original number. For instance, binary "1100" and dec
"11375" would result in "1 1 375" because 1 means put a space
in-between. This process will give you all combinations of the
original string in the different groups. Then you can extract the
numbers from the groups and see if they are primes...
Code:
private async void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length == 0) { return; }
textBox1.Enabled = false;
button1.Enabled = false;
textBox2.Clear();
String binary;
StringBuilder sb = new StringBuilder();
String input = textBox1.Text.Trim();
char[] digits = input.ToCharArray();
int padLength = input.Length - 1;
long combinations = (long)Math.Pow(2, padLength);
List<String> combos = new List<string>();
await Task.Run(() => {
for (long i = 0; i < combinations; i++)
{
binary = Convert.ToString(i, 2).ToString().PadLeft(padLength, '0');
char[] binaryDigits = binary.ToCharArray();
sb.Clear();
for (int s = 0; s < digits.Length; s++)
{
sb.Append(digits[s]);
if (s < (digits.Length - 1))
{
if (binaryDigits[s] == '1')
{
sb.Append(' ');
}
}
}
combos.Add(sb.ToString());
}
});
textBox2.Lines = combos.ToArray();
textBox1.Enabled = true;
button1.Enabled = true;
}
Output:
For very large inputs, you won't be able to compute the number of combinations using Math.Pow(), or any built-in methods for converting a decimal to a binary number. In those cases, you can "count manually" in binary by using a String directly and following the counting algorithm. You'd build the binary numbers using only String manipulation directly by inspecting each char to see if it is 1 or 0 and acting accordingly. You'll know you're done when you have a string of ones that has a length one less than the length of your input. It will run a lot slower than working with numbers directly.
I am new to java and I was learning how to convert from binary to decimal and vice versa. In the case of binary to decimal, I found out that I could use parseint, but I saw other methods that didn't use it, so I tried to implement them into my code, but it didn't work for me and I got stumped.
How would I be able to use a different method for calculating binary to decimal and implement it into my code?
Here is my code:
import java.util.Scanner;
class BinaryToDecimal {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String binaryString;
char choice;
String nextLine = "Empty";
int i = 0;
choice = 'Y';
try {
do {
System.out.print("Enter a binary number: ");
binaryString = sc.nextLine();
//Find the string count
int count = binaryString.length();
for (int j = 0; j< count; j++)
{
if (binaryString.charAt(j) != '1' && binaryString.charAt(j) != '0')
{
System.out.print("Enter a binary number: ");
binaryString = sc.nextLine();
count = binaryString.length();
j=0;
}
}
i = Integer.parseInt(binaryString);
if (i>0)
System.out.println("The decimal number is: " + Integer.parseInt(binaryString, 2));
System.out.println("Continue using the calculator? Only input Y or N");
String ln = sc.next();
if(ln.length()==1){
choice = ln.charAt(0);
}
else{
choice = 'N';
}
if (sc.hasNextLine()) {
nextLine = sc.nextLine();
}
} while (choice == 'Y');
} catch (NumberFormatException nfe) {
System.out.println("Invalid input");
}
}
}
Binary math involves adding 1 and multiplying by 2. I would use a regular expression to test if the input is valid. I would use an infinite loop and break when the user gives an answer besides y when prompted to continue. Putting that together, gives a simplified
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a binary number: ");
String binaryString = sc.nextLine();
// An int value consists of up to 32 0 and 1s.
if (!binaryString.matches("[01]+") || binaryString.length() > 32) {
continue;
}
int v = 0;
for (int i = 0; i < binaryString.length(); i++) {
v *= 2;
if (binaryString.charAt(i) == '1') {
v++;
}
}
System.out.println("The decimal number is: " + v);
System.out.println("Continue using the calculator? Only input Y or N");
String ln = sc.nextLine();
if (!ln.equalsIgnoreCase("Y")) {
break;
}
}
It looks like your missing you're missing the radix which the default I use is 2. Try this and let me know what happens
i = Integer.parseInt(binaryString,2);
There may be a nicer way of doing this, however this is the solution that I came up with. I took into account that the number can both be a positive and negative number and added checks for those cases. I also made sure to add exceptions for when an invalid binary number is entered.
public static int numberFromBinary(String binaryNumber) {
char[] array = binaryNumber.toCharArray();
boolean isNegative = false;
int result = 0;
if (array.length > 32) {
throw new NumberFormatException("An integer cannot be more than 32 bits long.");
}
if (array.length == 32) {
isNegative = array[0] == '1';
if (isNegative) {
result -= 1;
}
}
for (int i = 0; i < array.length && i != 31; i++) {
int worth = (int) Math.pow(2, i);
if (array[array.length - 1] != '1' && array[array.length - 1] != '0') {
throw new NumberFormatException("Binary bits can only be a '1' or a '0'.");
}
if (isNegative) {
if (array[array.length - 1] == '0') {
result -= worth;
}
} else {
if (array[array.length - 1] == '1') {
result += worth;
}
}
}
return result;
}
Here's a solution for converting a string representation of a binary number to a decimal number, without using Integer.parseInt(). This is based on
your original question text:
How would I be able to use a different method for calculating binary to decimal and implement it into my code?
And also a comment you added:
Also i did not want to use parseint
If you take a binary number and work your way from right to left, each digit is an increasing power of 2.
0001 = 2^0 = 1
0010 = 2^1 = 2
0100 = 2^2 = 4
1000 = 2^3 = 8
You can follow this same pattern: inspect each character position of a binary string input, and raise 2 to some power to get the decimal value represented by that bit being set to 1. Here's a simple bit of code that:
prompts for user input as a binary string
starting from right and working toward the left, it checks each character, comparing against '1'
if the character is in fact 1: take note of the position, raise 2 to the next power, and add that to the running total
Here's the code:
System.out.print("enter a binary number: ");
String binaryInput = new Scanner(System.in).next();
int decimalResult = 0;
int position = 0;
for (int i = binaryInput.length() - 1; i >= 0; i--) {
if (binaryInput.charAt(i) == '1') {
decimalResult += Math.pow(2, position);
}
position++;
}
System.out.println(binaryInput + " --> " + decimalResult);
And a few sample runs:
enter a binary number: 1111
1111 --> 15
enter a binary number: 101010101
101010101 --> 341
enter a binary number: 100000000000
100000000000 --> 2048
I tried to write a method (for kicks) that would sum up the digits at even places using Java recursion.
For example, the number 23495 would return 3+9 = 12.
I am unsuccessful and would appreciate hints or what I'm doing wrong.
int sumEven = 0;
int sumOdd = 0;
int i = 1;
if (n == 0)
return sumEven;
if (n != 0) {
if (i % 2 == 0)
{
i++;
sumEven += n % 10;
}
else
{
i++;
sumOdd += n % 10;
}
}
return sumEven + getEven (n/=10);
The problem is you're trying to do too much - take a look at my comment on the Q
A recursive method needs an input that contains everything it needs to work with, a return value, and an execution path where it calls itself until something happens that means it doesn't need to call itself any more - without this bit it will recourse until it overflows the stack
int sumEveryOtherDigit(int input){
if(input >= 100)
return input%10 + sumEveryOtherDigit(input/100);
else
return input%10;
}
This takes the input , and if there is any point to running again (if the input is at least 100) takes the rightmost digit plus running itself again with a smaller number
Eventually the number gets so small that there isn't any point running itself again so it just returns without running itself again and that is how the recursion stops
Now from your comment on another answer it seems you want to determine even and odd as working from the left so we need to either start with the number (1630) or the number divided by ten (23495 -> 2349) - basically to start the recursion going we always want to pass in a number with an even number of digits
int num = 23495;
int numOfDigits = (int)Math.log10(num)+ 1;
if(numOfDigits%2==0)
result = sumEveryOtherDigit(num);
else
result = sumEveryOtherDigit(num/10);
You should iterate over the digits of the input number, and then sum the remainder mod 10 only for even position digits:
int input = 23495;
input /= 10;
int sum = 0;
while (input > 0) {
sum += input % 10; // add last even digit
input /= 100; // advance by two digits, to the next even digit
}
System.out.println("sum of even digits of input is: " + sum);
This prints:
sum of even digits of input is: 12
I'd like to know how to remove numbers from an integer. For example, if I have the number 23875326, I want to remove the odd numbers, and get the result of 2826.
I've been trying to break each number to check if it's even or odd using a while loop, but I don't know how to merge the numbers into one integer. One important thing is, I'd like to do it without using strings, as it doesn't teach me anything new that way.
I actually think that dealing with a string of numbers is preferable, not only from a code readability point of view, but also possibly from a performance view. That being said, if we absolutely cannot use strings here, then it is still possible to work directly with the integer input.
We can examine each tens digit of the input number using num % 10. Should that digit be even, we can add it to the output number, otherwise do not add it. Note that at each iteration we need to scale the digit by 10 to the correct exponent.
Here is a working code snippet:
int length = (int) (Math.log10(num) + 1); // finds the number of digits
int output = 0;
int counter = 0;
for (int i=0; i < length; ++i) {
if ((num % 10) % 2 == 0) {
output += (num % 10) * Math.pow(10, counter);
++counter;
}
num = num / 10;
}
System.out.println(output);
2826
Demo
I used #Tim Biegeleisen code and changed it a bit, removed some code and changed the for loop to while loop:
int output = 0;
int counter = 0;
System.out.println("Enter a number");
int num = s.nextInt();
while (num != 0) {
if ((num % 10) % 2 == 0) {
output += (num % 10) * Math.pow(10, counter);
++counter;
}
num = num / 10;
}
System.out.println(output);`
1. long number = 564;
2. String str = number+"";
3. char[] num = str.toCharArray();
4. number = number - num[0];
/* The value of number is 511 */
I am trying to subtract the first digit of the number from the number using this piece of code.
During debugging, i found out that the value of num[0] was 53. Can anyone explain what am i missing here.
I would suggest you to change your fourth line to this:
number = number - Long.parseLong(Character.toString(num[0]));
Basically, what is happening here is that I first convert the char (num[0]) to a string, then parsed the string to a long.
ALternatively, you don't even need to convert the string to a char array! Use charAt() to get the char:
number = number - Long.parseLong(Character.toString(str.charAt(0)));
When you are using the binary operator "-" the smaller datatype, in this case char, is promoted to long which returns the ASCII value of num[0] ('5') which is 53. To get the actual face value of num[0] convert it to String and parse it to Long as Sweeper has pointed out.
It just feels wrong to convert a number to a string, extract the first char, convert back to number and subtract. Why don't you extract the first digit while working with numbers directly. Something like this would do:
long number = 564;
int digits = 0;
assert (number > 0);
for (long num = number; num > 1; num = num / 10 ) {
digits += 1;
}
int firstDigit = (int) (number / Math.pow(10, digits -1));
number = number - firstDigit;
System.out.println(number);
If you want to get all digits:
long number = 564;
int digits = 0;
assert (number > 0);
for (long num = number; num > 1; num = num / 10 ) {
digits += 1;
}
for (int digit = digits - 1; digit >= 0; digit--) {
int currentDigit = (int) (number / Math.pow(10, digit)) % 10;
System.out.println(currentDigit);
}