Edited Java adds 4-digit numbers

I want to add 4 digit numbers 1 or 2 digits using Java.

i1=2 i2=33 i3=12 i4=10 

Result: 12 (2 + 3 + 3 + 1 + 2 + 1 + 0)

How could I do this?

-9
source share
4 answers

Here are some tips you might need:

1) If you use / for arguments that will be integer, then your result will also be integer.

Example:

 int x = 7/2; System.out.println(x); 

output: 3 (not 3.5 )

So, to get rid of the last digit of an integer, you can simply divide this number by 10, for example

 int x = 123; x = x/10; System.out.println(x); 

Output: 12

2) Java also has a modulo operator that returns a reminder from the division, for example 7/2=3 and 1 will be a reminder. This % operator

Example

 int x = 7; x = x % 5; System.out.println(x); 

Output: 2 , because 7/5=1 (2 remains)

So, to get the last digit from an integer, you can just use % 10 as

 int x = 123; int lastDigit = x%10; System.out.println(lastDigit); 

Output: 3

Now try to combine this knowledge. Get the last digit of the number, add it to the amount, delete this last digit (repeat until there are more digits).

+3
source

You want to do it like this:

 public static void main(String[]args){ int num=1234,sumOfDigits=0; while(num!=0){ sumOfDigits+=num%10; num/=10; } System.out.println("Sum of digits is : " + sumOfDigits); } 

Things, to understand%, give the rest of the number, so when you do 1234% 10, it gives 4. This is the last digit.
num / = 10 means num = num / 10; so this will be 1234/10 will be 123, not 123.4, since it is an int int division.

+1
source

Create a function that will calculate the sum of the digits:

 int getDigitSum(int n) { return Math.floor(n/10) + n % 10; } 

Then use it for each value and summarize the results.

Please note that I wrote this method only for working with numbers less than 100. If necessary, you can easily create a more general method.

0
source

I tried to achieve the goal on paper, though. :-). Please try this

 int addition=0; int num=243; while(num>9){ int rem; rem=num%10; addition=addition+rem; num=num/10; if(num<9) { addition+=num; num=addition; addition=0; } } System.out.println(num); 
0
source

Source: https://habr.com/ru/post/1204915/


All Articles