Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.InputMismatchException;
- import java.util.Scanner;
- public class PowerPrint
- {
- // Unicode character codes for superscripts of {0, 1, 2,..., 9}
- public static final char[] SUPERS = {
- '\u2070', '\u00B9', '\u00B2', '\u00B3', '\u2074',
- '\u2075', '\u2076', '\u2077', '\u2078', '\u2079'
- };
- public static void main( String[] args ) {
- Scanner scan = new Scanner( System.in );
- int i = -1; // initialize to indicate bad input
- String prompt = "an integer in the set {0, 1, 2,..., 2\u00B3\u00B9-1}.";
- System.out.println( "Enter " + prompt );
- // nextInt() fails for input outside of int range [-2³¹, 2³¹-1]
- try { i = scan.nextInt(); }
- // don't need to repair anything, since i already indicates bad input
- catch ( InputMismatchException e ) {;}
- // refuse input outside range [0, 2³¹-1]
- if (0 > i || 2147483647 < i) {
- System.out.println( "I said \"" + prompt.toUpperCase() + "\" \nBye." );
- return;
- }
- System.out.println( getPowersOf2( i, 0, "" ));
- }
- // convert decimal integer in range [0, 2³¹-1] into String of
- // form: 2ⁿ + 2ⁿ⁻¹ + 2ⁿ⁻² +...+ 2⁰, e.g., 67 ==> 2⁶ + 2¹ + 2⁰
- public static String getPowersOf2( int i, int n, String s ) {
- // get integer portion of division by 2
- int r = i/2;
- // if current i has remainder under division by 2, - (1 == i%2) -
- // then there is component to be added to sum, i.e., 2ⁿ for
- // current value of n; if there's more processing to be done -
- // (0 < r) - add leading " + " to the String as well
- if (1 == i%2) s = ((0 < r) ? " + " : "") + "2" + getSuperscript( n ) + s;
- // if more to process, recurse - otherwise, return s
- return (0 < r) ? getPowersOf2( r, ++n, s ) : s;
- }
- // compose superscript n from elements of SUPERS
- public static String getSuperscript( int n ) {
- return ((9 < n) ? "" + SUPERS[ (int) Math.floor( n/10 ) ] : "") +
- SUPERS[ n%10 ];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement