Incrementing in java without arithmetic operation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Incrementing in java without arithmetic operation

how to increment a for loop in java without using any arithmetic operator??

14th Aug 2018, 3:25 PM
Keerttik Titan
Keerttik Titan - avatar
4 Answers
+ 4
to increment a number by 1 without using arithmetic operators, do: uint i = ...; uint m = 1; while(i & m) { i &= ~m; m <<= 1; } i |= m; note that this works only for unsigned integers, but successfully increases "i" by 1
14th Aug 2018, 3:55 PM
hinanawi
hinanawi - avatar
+ 3
hinanawi using a for loop.. not a while.. but it was a good answer..
14th Aug 2018, 6:01 PM
Keerttik Titan
Keerttik Titan - avatar
+ 1
hinanawi Honestly, I've never seen <<= used in Java before. Nice one 👍
14th Aug 2018, 4:12 PM
Dlite
Dlite - avatar
+ 1
Keerttik Titan well this can be used to increment the integer that's used in the for loop (replace "i++" with this for example, this is just how to increment by 1), which is how i interpreted the question
14th Aug 2018, 7:08 PM
hinanawi
hinanawi - avatar