Reverse and sum the number occurrence in string - java
All you really need to do is :
String input = "We have 55 guests in room 38";
int sum = 0;
String[] split = input.split(" "); // split based on space
for (int i = 0; i < split.length; i++) {
if (split[i].matches("[0-9]+")) {
sum = sum + Integer.parseInt(new StringBuffer(split[i]).reverse().toString());
}
}
System.out.println(sum);
Explanation:
- Here we use regex to check if the String split contains only
digits. - Now we reverse the String and then parse it to an int before
summing.
Check if a number can be formed by sum of a number and its reverse
All the previous answers are not really a check. It's more a brute force try and error.
So let's do it a little bit smarter.
We start with a number, for example 246808642. we can reduce the problem to the outer 2 place values at the end and start of the number. Let us call this values A and B at the front and Y and Z on the back. the rest, in the middle, is Π. So our number looks now ABΠYZ with A = 2, B = 4, Π = 68086, Y = 4 and Z = 2. (one possible pair of numbers to sum up for this is 123404321). Is A equal to 1, this is only possible for a sum greater 10 (An assumption, but i guess it works, some proof would be nice!).
so if it is a one, we know that the second last number is one greater by the carry over. So we ignore A for the moment and compare B to Z, because they should be the same because both are the result of the addition of the same two numbers. if so, we take the remaining part Π and reduce Y by one (the carry over from the outer addition), and can start again at the top of this chart with Π(Y-1). Only a carry over can make B one bigger than Z, if it's so, we can replace B by one and start with 1Π(Y-1) at the top. B-1!=Z and B!=Z, we can stop, this isnt possible for such a number which is the sum of a number and its reversed.
If A != 1, we do everything similiar as before but now we use A instead of B. (I cut this here. The answer is long enough.)
The code:
import time
def timing(f):
def wrap(*args, **kwargs):
time1 = time.time()
ret = f(*args, **kwargs)
time2 = time.time()
print('{:s} function took {:.3f} ms'.format(f.__name__, (time2-time1)*1000.0))
return ret
return wrap
@timing
def check(num):
num = str(num)
if (int(num) < 20 and int(num)%2 == 0) or (len(num) ==2 and int(num)%11 == 0):
return print('yes')
if len(num) <= 2 and int(num)%2 != 0:
return print('no')
# get the important place values of the number x
A = num[0]
B = num[1]
remaining = num[2:-2]
Y = num[-2]
Z = num[-1]
# check if A = 1
if A == '1':
# A = 1
# check if B == Z
if B == Z:
# so the outest addition matches perfectly and no carry over from inner place values is involved
# reduce the last digit about one and check again.
check(remaining + (str(int(Y)-1) if Y != '0' else '9'))
elif int(B)-1 == int(Z):
# so the outest addition matches needs a carry over from inner place values to match, so we add to
# to the remaining part of the number a leading one
# we modify the last digit of the remaining place values, because the outest had a carry over
check('1' + remaining + (str(int(Y)-1) if Y != '0' else '9'))
else:
print("Not able to formed by a sum of a number and its reversed.")
else:
# A != 1
# check if A == Z
if A == Z:
# so the outest addition matches perfectly and no carry over from inner place values is involved
check(B + remaining + Y)
elif int(A) - 1 == int(Z):
# so the outest addition matches needs a carry over from inner place values to match, so we add to
# to the remaining part of the number a leading one
# we modify the last digit of the remaining place values, because the outest had a carry over
check('1' + B + remaining + Y)
else:
print("Not able to formed by a sum of a number and its reversed.")
@timing
def loop_check(x):
for i in range(x + 1):
if i == int(str(x - i)[::-1]) and not str(x - i).endswith("0"):
print('yes, by brute force')
break
loop_check(246808642)
check(246808642)
Result:
yes, by brute force
loop_check function took 29209.069 ms
Yes
check function took 0.000 ms
And another time we see the power of math. Hope this work for you!
How to reverse a long sum without losing the first digit after the sum reverse?
Instead my program drops the zero and return a result of
987654321987654321. Is my while loop math off?
the issue is not with your code, you simply cannot have integer values with a leading 0
. if you want to keep the leading 0
you'll need to store it as a string.
StringBuilder reverseSum = new StringBuilder(Long.toString(sum));
System.out.println("The reversed sum is " + reverseSum.reverse());
if you want the StringBuilder
as a string:
String tempValue = reverseSum.toString();
EDIT
here is the full code to accomplish the task at hand:
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number: ");
long n1 = sc.nextLong();
System.out.println("Enter second number: ");
long n2 = sc.nextLong();
long sum = n1+n2;
StringBuilder reverseSum = new StringBuilder(Long.toString(sum));
System.out.println("The reversed sum is " + reverseSum.reverse());
}
reversing a number using do-while
do this instead
import java.util.*;
public class Main {
static int replace(int number){
if (number %10 == 0)
return number += 1;
return number;
}
static int Convert(int number){
if (number == 0)
return 0;
else
return replace(number);
}
public static void main(String[] args) {
int number;
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number : ");
number = kb.nextInt();
int a = 0, m = 0, sum = 0;
number = replace(number);
System.out.println("replace:" + number);
do{
a = number % 10;
m = m * 10 + a;
sum = sum + a;
number /= 10;
}
while( number > 0);
System.out.println("Reverse:"+m);
System.out.println("Sum of digits:"+sum);
}
}
Your code is fundamentally wrong because of the way you are replacing your numbers.
Changes made:
- Changed replacing algorithm (You cannot change all 0 values to 1 that is wrong and why you got the wrong values)
- Replace the number before you enter the loop. (You don't need to replace every iteration of the loop at 3 different place)
Expected output:
how to calculate the sum of digits for a number in java?
That's because you are sharing same number in both reverse and sum method and when you first call reverse method you go on dividing the number until 0 and hence when you come to sum method, your number is 1 and hence sum is 0.
Inorder to rectify this, i would suggest you define local variable called mynumber like:
public int fill() {
System.out.println("enter the number");
Scanner in = new Scanner(System.in);
num = in.nextInt();
if (num < 0) {
System.out.println("enter a positive number");
}
int myNumber = num;
while (myNumber != 0) {
reverse = reverse * 10;
reverse = reverse + myNumber % 10;
myNumber = myNumber / 10;
}
System.out.println("your reverse number is : " + reverse);
return num;
}
OUTPUT:
enter the number
1234
your reverse number is : 4321
sum of digits: 10
JAVA sum of the two numbers is the reverse of the product error
while (input != 0)
{
last_digit = input % 10;
if (last_digit % 2 != 0) {
reversedNum = reversedNum * 10 + last_digit;
}
input = input / 10;
}
Determining if an integer can be expressed as a palindromic sum
In the stress and the hurry of an interview, I would have certainly found a dumb and naive solution.
pseudo code
loop that array containing the numbers
Looping from nb = 0 to (*the number to test* / 2)
convert nb to string and reverse the order of that string (ie : if you get "29", transform it to "92")
convert back the string to a nb2
if (nb + nb2 == *the number to test*)
this number is special. Store it in the result array
end loop
end loop
print the result array
function IsNumberSpecial(input){ for (let nb1 = 0; nb1 <= (input / 2); ++nb1) { let nb2 = parseInt(("" + nb1).split("").reverse().join("")); // get the reverse number if (nb2 + nb1 == input) { console.log(nb1 + " + " + nb2 + " = " + input); return (true); } } return (false);}
let arr = [22, 121, 42];
let len = arr.length;let result = 0;
for (let i = 0; i < len; ++i){ if (IsNumberSpecial(arr[i])) ++result;}
console.log(result + " number" + ((result > 1) ? "s" : "") + " found");
Method to sum and reverse a single input in Java?
There is something wrong with your code:
You never put user input inside num array and for loop was just an active wait,
try it now:
public static void main(String[] args)
{
//call for input
System.out.println("Please Enter a 3-digit number..");
Scanner in = new Scanner(System.in);
int val = in.nextInt();
int[] num = new int[3];
if(val<=99) // is not a 3 digit number
return;
int i =2;
while (val > 0) {
num[i]=(val%10);
val = val / 10;
i--;
}
System.out.println("The Sum of the numbers is " + (num[0] + num[1]+ num[2]));
System.out.println("The Reverse of the numbers is " + num[2] +""+ num[1]+""+ num[0]);
}
With input 1 - 2 -3 gives you:
Please Enter a 3-digit number..
1
2
3
The Sum of the numbers is 6
The Reverse of the numbers is 321
How to output a reverse expanded sum
Think this does what you linked in the image assuming it only takes positive integers given "Enter a positive integer.\n"
public static int printSum(int n) {
int sum = 0;
for(int x = 0; x < n; x++){
sum += n - x;
if(x != n - 1){
System.out.print((n - x) + "+");
}
else{
System.out.print((n - x) + "=" + sum);
}
}
return sum;
}
Related Topics
On Selenium Webdriver How to Get Text from Span Tag
Set Zoom Level to 100% in Selenium Webdriver When Default Is Not 100
How to Hide a Request Field in Swagger API
Maven Builds Are Working, But Junit Is Throwing a Nosuchmethoderror
Error Starting Applicationcontext in Spring Boot App
How to Skip @Postconstruct When Unit Testing
How to Sort Integer Digits in Ascending Order Without Strings or Arrays
In Firebase After Uploading Image How to Get Url
How to Get the Autoincremented Id When I Insert a Record in a Table Via Jdbctemplate
How to Convert Date Which I Got from Firebase Server as Am Getting Error Date
Calculate the Number of Items Displayed by Recyclerview and Place in a Textview
Jsp and CSS File Not Loading in Browser Java Webapp