Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Examples

By: a guest on Feb 4th, 2011  |  syntax: Java 5  |  size: 1.30 KB  |  views: 1,750  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1.     public static int getCountOfOnes(int n) {
  2.         /*
  3.          Please implement this method to
  4.          return the number of '1's in the binary representation of n
  5.          for any integer n, where n > 0
  6.  
  7.          Example: for n=6 the binary representation is '110' and the number of '1's in that
  8.          representation is 2
  9.  
  10.         */
  11.         int cnt = 0;
  12.         String s = Integer.toBinaryString(n);
  13.         System.out.println("Binary String = " + s);
  14.         for(int i = 0; i < s.length(); i++){
  15.                 String j = Character.toString(s.charAt(i));
  16.  
  17.                 if (Character.isDigit(s.charAt(i))){
  18.                         if (j.equalsIgnoreCase("1")) {
  19.                                 cnt++;
  20.                         }
  21.                 }
  22.         }
  23.        
  24.         return cnt;
  25.     }
  26.  
  27.     // Please do not change this interface
  28.     interface ListNode {
  29.         int getItem();
  30.         ListNode getNext();
  31.         void setNext(ListNode next);
  32.     }
  33.  
  34.     public static ListNode reverse(ListNode node) {
  35.         /*
  36.           Please implement this method to
  37.           reverse a given linked list.
  38.          */
  39.         ListNode prev = null;
  40.         ListNode cur = null;
  41.         ListNode next = null;
  42.         prev = node;
  43.         cur = node.getNext();
  44.         prev.setNext(null);
  45.         while(cur.getNext()!=null){
  46.                 next = cur.getNext();
  47.                 cur.setNext(prev);
  48.         }
  49.        
  50.         return cur;
  51.     }