0

I want to take 904 and to do 9 + 0, but 904 is in an int variable. I did try the following code, but if the user change the number i, it doesn't always work.

int i = 567;
int j = (i - (i % 100)) / 100 + ((i % 100) - (i % 10)) / 10;
System.out.println(j);
yshavit
  • 42,327
  • 7
  • 87
  • 124
user1996
  • 13
  • 3

3 Answers3

3

Try this approach

int i=567;
String s=i+""; // Puts `+` into concatenation mode.
int a=Integer.parseInt(s.charAt(0)+"");
int b=Integer.parseInt(s.charAt(1)+"");
System.out.println(a+b);
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
Karan
  • 448
  • 4
  • 9
  • 2
    Please don't perform `String` promotion by concatenation, `Integer.toString(i)` and `Character.toString(s.charAt(0))` and so on. (or `Character.digit(s.charAt(0), 10)` and skip the `parseInt`) – Elliott Frisch Oct 12 '17 at 16:56
  • 1
    Other than the string concatenation, this is a good answer. It's not the most efficient way to solve the problem, but it's the clearest and most concise way, and in practice it's probably fast enough (unless this is being done in a tight loop). A note to the OP, though: you should probably do a quick check that (a) there are at least two digits and (b) that the number is positive (or else `s.chartAt(0)` will be `'-'`). – yshavit Oct 12 '17 at 16:58
  • The numerical answer is better: this will fail for a negative integer. – Bathsheba Oct 12 '17 at 17:03
  • 1
    @Bathsheba [`Math.abs(int)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#abs-int-) should fix that bug. I'd go with the clearest and easiest to read code myself. – Elliott Frisch Oct 12 '17 at 17:04
  • I have a dislike for any code that uses strings for essentially numerical calculations. – Bathsheba Oct 12 '17 at 17:05
  • 2
    @Bathsheba I have that same instinct, but on the flip side: this works for any integer >= 100 and is _instantly_ clear on exactly what it does. That offsets the disadvantage. Besides, as soon as you're saying "first two digits" you're thinking of the number not as a single value, but as a string of digits. – yshavit Oct 12 '17 at 17:08
  • Until some dude changes their locale - or a future version of java permits it - in such a way as to introduce thousands separators. It's slow. It's dangerous. You have to check the docs to see if any of my suspicions are not unfounded. It's symptomatic of programming indolence. – Bathsheba Oct 12 '17 at 17:09
  • @Bathsheba I don't believe locales affect `Integer.toString`, and it's highly unlikely that the JDK folks would break backwards compatibility to change that. So now you're down to "I don't like it" and "I'd prefer a premature optimization (that either only works for values 100 <= x < 1000, or has to add more bug-prone code)." Haven't sold me, personally. :) But, to each their own. – yshavit Oct 12 '17 at 17:14
  • I’m not mad about strings for this purpose, the only thing is that toString() is intrisecally linearly complex. – NoImaginationGuy Oct 12 '17 at 17:28
  • 1
    I quite like the `i + ""` idiom. Reminds me of the elegant `""s + ...` type idioms of C++14. – Bathsheba Oct 12 '17 at 21:18
1

You can pick up the third digit.

int d3 = x / 100;

And the second digit:

int d2 = (x / 10) % 10;

Note: I’m assuming 100 <= x <= 999

Update: I wanted to search for a fast solution giving the number of digits and this question gave a (potentially) good solution:

x = (int)Math.abs(x); // this is for negative numbers
int digits = (int)Math.log10(x) + 1;

This extends the hypothesis of 100 <= x <= 999:

int div = Math.pow(10, digits - 1);
int firstDigit = x / div;
div /= 10;
int secondDigit = (x / div) % div;

This should work for any x != 0. There may be faster solutions though.

NoImaginationGuy
  • 1,795
  • 14
  • 24
0

One way is to make a loop, getting the last digit (using i%10), storing that, and dividing i by 10 before looping again.

void PrintSumFirstTwoDidgets(int i){
    if(i < 10) {
        throw new IllegalArgumentException("i must be at least 10.");
    }
    int secondDigit;
    int firstDigit = i % 10;
    do {
        i /= 10;
        secondDigit = firstDigit;
        firstDigit = i % 10
    } while(i > 0);
    System.out.println(firstDigit + secondDigit);
}
ILMTitan
  • 10,751
  • 3
  • 30
  • 46