Share on Google+Share on Google+

Check whether the sum of alternate digit of a number is palindrome or not.

Advertisement
In this section, you will learn how to check whether the sum of alternate digit of a number is palindrome or not.

Check whether the sum of alternate digit of a number is palindrome or not.

In the previous section, we have discussed about the number palindromes. Here we are going to check whether the sum of the alternate digit of a number entered by the user is palindrome or not. So, firstly we have to find the sum of the alternate digits of number (like if a number is 23456, the sum of alternate digit of this number be 2+4+6 i.e 12) and then check whether this sum is palindrome or not.

Here is the code:

import java.math.*;
import java.util.*;

class CheckSumIsPalindrome {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("Enter Number: ");
		BigInteger bi = input.nextBigInteger();
		int num = 0;
		String strSum = bi.toString();
		for (int i = 0; i < strSum.length(); i += 2) {
			char ch = strSum.charAt(i);
			int n = Integer.parseInt(Character.toString(ch));
			num += n;
		}
		System.out.println("Sum of Alternate digits is: " + num);
		int n = num;
		int reversedNumber = 0;
		for (int i = 0; i <= num; i++) {
			int r = num % 10;
			num = num / 10;
			reversedNumber = reversedNumber * 10 + r;
			i = 0;
		}
		if (n == reversedNumber) {
			System.out.print("Number is palindrome!");
		} else {
			System.out.println("Number is not palindrome!");
		}
	}
}

Advertisements

Advertisement

Posted on: January 15, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.