Java int addition - the long way

  • Context: Java 
  • Thread starter Thread starter NiaSphinx
  • Start date Start date
  • Tags Tags
    Addition Java
Click For Summary

Discussion Overview

The discussion revolves around performing integer addition in Java by manually accessing and manipulating the individual digits of integers, akin to traditional addition methods. Participants explore methods for extracting digits from integers, considering both base 10 and other bases.

Discussion Character

  • Exploratory, Technical explanation

Main Points Raised

  • One participant seeks a method to split integers for manual addition in Java, specifically accessing individual digits.
  • Another participant suggests using integer division and modulo operations to extract digits in base 10, providing a specific example of the process.
  • A subsequent reply questions whether the proposed method can be adapted for bases other than 10.
  • A further contribution proposes a generalized formula for obtaining digits in any base, indicating how to calculate the nth digit of a number using floor division and modulo operations.

Areas of Agreement / Disagreement

Participants have not reached a consensus, as the discussion includes varying approaches to digit extraction and the applicability of these methods to different bases.

Contextual Notes

The discussion does not clarify assumptions regarding the handling of negative integers or the implications of using bases other than 10.

NiaSphinx
Messages
4
Reaction score
0
Hi guys,

I'm trying to figure out a way to split up integers so I can do addition the old school way in Java.
E.g.:
1234
1234
+_____
2468

So you know start at the 4's and then add them up and move left etc.
Does anyone have any ideas on how I access the different digits of an int?

Thanks
 
Technology news on Phys.org
I don't know if there is some nice routine for this, but there is always the oldfashioned dirty way: to access the 10n digit (i.e. for n = 0 you get the units, for n = 1 the tens, etc) you can integer-divide by 10n and then take the result modulo 10.
For example:

1234 / 100 = 12 (as integer division produces an integer by chopping off the decimal part)
12 % 10 = 2
 
Ah that does sound like a good way of doing it.
Can it work the same if the base is not 10?
 
I suppose in base b, one can still obtain the digits at the nth position (starting from n = 0 on the right) of a number N as

[tex]\operatorname{digit}_n(N) = \left[ N / b^n \right] \text{ mod } b[/tex]
where the square brackets denote the floor of the division.
 

Similar threads

Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
5K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 29 ·
Replies
29
Views
4K
Replies
9
Views
8K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
Replies
2
Views
2K