+ 1

How to get first 4 digits of integers reversed, instead of whole ( if i want o/p to be 4321)

class Main { public static void main(String[] args) { int num = 1234567, reversed = 0; for(;num != 0; num /= 10) { int digit = num % 10; reversed = reversed * 10 + digit; } System.out.println("Reversed Number: " + reversed); } } O/p- Reversed Number:7654321

2nd Apr 2022, 3:20 PM
yash kurale
2 Réponses
+ 4
Take another variable count for counting number digits, and now here equal to 7 You need only 4 digits so 7-4=3 and divide reversed number ny 10^3 which gives you dividend 7654. hope it helps.... edit: from 1234567, reverse = 7654321 for 7654 => 7654321/1000 (last 4 digits) for 4321 => 7654321%10000 (first 4 digits) or else do => 1234567/1000 => 1234, reverse it..
2nd Apr 2022, 3:32 PM
Jayakrishna 🇮🇳