Share Pastebin
Guest
Public paste!

Untitled

By: a guest | Mar 14th, 2010 | Syntax: Java | Size: 1.24 KB | Hits: 78 | Expires: Never
Copy text to clipboard
  1. public class test
  2. {
  3.  
  4.         public static void main(String [] args)
  5.         {
  6.                
  7.                 long total = 0;
  8.                 for (int i = 1; i < 1024; i++)
  9.                 {
  10.                         long l = Long.toBinaryString(i).length();
  11.                         long f = FlipBits(i, l);
  12.                         long n = (i << l) + f;
  13.                         long n2 = (i << (l-1));
  14.                        
  15.                         if ((f & (long)Math.pow(2, l-1)) != 0)
  16.                                 n2 += (f-(long)Math.pow(2, l-1));
  17.                         else
  18.                                 n2 += f;
  19.  
  20.                         if (n > 1000000) break;
  21.                        
  22.                         if (n == revDigits(n)) total += n;
  23.                         if (n2 == revDigits(n2)) total += n2;
  24.                 }
  25.                 System.out.println("ANSWER: " + total);
  26.         }
  27.        
  28.         public static long revDigits(long n)
  29.         {
  30.                 long t = 0;
  31.                 while (n > 0)
  32.                 {
  33.                         long f = n%10;
  34.                         n -= f;
  35.                         t += f;
  36.                         n /= 10;
  37.                         if (n > 0) t *= 10;
  38.                 }
  39.                 return t;
  40.         }
  41.        
  42.         public static long FlipBits(long n, long l)
  43.         {
  44.                 long a = 0;
  45.                 for (long i = (l-1); i >= 0; --i) {
  46.                         if ((n & (long)Math.pow(2, i)) != 0) {
  47.                                 a += Math.pow(2, ((l-i)-1));
  48.                         }
  49.                 }
  50.  
  51.                 return a;
  52.         }
  53.  
  54. }