Advertisement
richarduie

PowerPrint

Apr 6th, 2013
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.91 KB | None | 0 0
  1. import java.util.InputMismatchException;
  2. import java.util.Scanner;
  3.  
  4. public class PowerPrint
  5. {
  6.     // Unicode character codes for superscripts of {0, 1, 2,..., 9}
  7.     public static final char[] SUPERS = {
  8.         '\u2070', '\u00B9', '\u00B2', '\u00B3', '\u2074',
  9.         '\u2075', '\u2076', '\u2077', '\u2078', '\u2079'
  10.     };
  11.  
  12.     public static void main( String[] args ) {
  13.         Scanner scan = new Scanner( System.in );
  14.  
  15.         int i = -1;     // initialize to indicate bad input
  16.         String prompt = "an integer in the set {0, 1, 2,..., 2\u00B3\u00B9-1}.";
  17.         System.out.println( "Enter " + prompt );
  18.         // nextInt() fails for input outside of int range [-2³¹, 2³¹-1]
  19.         try { i = scan.nextInt(); }
  20.         // don't need to repair anything, since i already indicates bad input
  21.         catch ( InputMismatchException e ) {;}
  22.         // refuse input outside range [0,  2³¹-1]
  23.         if (0 > i || 2147483647 < i) {
  24.             System.out.println( "I said \"" + prompt.toUpperCase() +  "\" \nBye." );
  25.             return;
  26.         }
  27.  
  28.         System.out.println( getPowersOf2( i, 0, "" ));
  29.     }
  30.    
  31.     // convert decimal integer in range [0, 2³¹-1] into String of  
  32.     // form: 2ⁿ + 2ⁿ⁻¹ + 2ⁿ⁻² +...+ 2⁰, e.g., 67 ==> 2⁶ + 2¹ + 2⁰
  33.     public static String getPowersOf2( int i, int n, String s ) {
  34.         // get integer portion of division by 2
  35.         int r = i/2;
  36.         // if current i has remainder under division by 2, - (1 == i%2) -
  37.         // then there is component to be added to sum, i.e., 2ⁿ for
  38.         // current value of n; if there's more processing to be done -
  39.         // (0 < r) - add leading " + " to the String as well
  40.         if (1 == i%2) s = ((0 < r) ? " + " : "") + "2" + getSuperscript( n ) + s;
  41.         // if more to process, recurse - otherwise, return s
  42.         return (0 < r) ? getPowersOf2( r, ++n, s ) : s;
  43.     }
  44.     // compose superscript n from elements of SUPERS
  45.     public static String getSuperscript( int n ) {
  46.         return ((9 < n) ? "" + SUPERS[ (int) Math.floor( n/10 ) ] : "") +
  47.             SUPERS[ n%10 ];
  48.     }
  49.  
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement