Esempio n. 1
1
  // -------------------  Solution 3 ------------------------//
  // split the string by hand (same algorithm as above 2)
  public String reverseWords3(String s) {
    // validate input
    if (s == null || s.length() == 0) {
      return "";
    }

    // iterate backwards and append words one-by-one
    StringBuilder reversedStr = new StringBuilder();
    StringBuilder curWord = new StringBuilder();
    for (int i = s.length() - 1; i >= 0; i--) {
      if (s.charAt(i) == ' ') { // skip all spaces
        continue;

      } else { // for non-spaces
        // starter of a new word
        if (i == s.length() - 1 || s.charAt(i + 1) == ' ') {
          if (curWord.length() > 0) {
            reversedStr.append(curWord.reverse().toString() + " ");
          }
          curWord = new StringBuilder();
        }
        curWord.append(s.charAt(i));
      }
    }
    // don't forget to add the last word!
    reversedStr.append(curWord.reverse().toString());
    return reversedStr.toString();
  }
Esempio n. 2
1
  public static void add(String a, String b) {
    if (a.length() != b.length() && a.length() < 32 && b.length() < 32) {
      if (a.length() > b.length()) {
        StringBuilder z = new StringBuilder(b);
        z.reverse();
        while (z.length() < a.length()) {
          z.append(0);
        }
        z.reverse();
        b = z.toString();
      } else {
        StringBuilder z = new StringBuilder(a);
        z.reverse();
        while (z.length() < b.length()) {
          z.append(0);
        }
        z.reverse();
        a = z.toString();
      }
    }

    if (b.length() > 31) {
      b = "overflow";
    }
    if (a.length() > 31) {
      a = "overflow";
    }

    boolean cero = true;
    int i = 0;
    while (i < b.length() && cero == true) {
      if (b.charAt(i) != '0') {
        cero = false;
      }
      i++;
    }

    System.out.println(a + " " + b);

    if (!cero && !a.equals("overflow") && !b.equals("overflow")) {
      StringBuilder c = new StringBuilder();
      StringBuilder d = new StringBuilder();
      for (int j = 0; j < a.length(); j++) {
        if (a.charAt(j) != b.charAt(j)) {
          c.append(1);
        } else {
          c.append(0);
        }
        if (a.charAt(j) == '1' && b.charAt(j) == '1') {
          d.append(1);
        } else {
          d.append(0);
        }
      }
      a = c.toString();
      b = mult2Bin(d.toString());
      add(a, b);
    }
  }
 /** 分割电话号码 */
 private String splitPhoneNum(String phone) {
   StringBuilder builder = new StringBuilder(phone);
   builder.reverse();
   for (int i = 4, len = builder.length(); i < len; i += 5) {
     builder.insert(i, ' ');
   }
   builder.reverse();
   return builder.toString();
 }
 public static String toReverseText(String text) {
   StringBuilder newString = new StringBuilder();
   StringBuilder tempString = new StringBuilder();
   for (int i = 0; i < text.length(); i++) {
     if (text.charAt(i) == ' ') {
       newString.append(tempString.reverse()).append(" ");
       tempString.delete(0, tempString.length());
     } else {
       tempString.append(text.charAt(i));
     }
   }
   newString.append(tempString.reverse());
   return newString.toString();
 }
  /**
   * the method reverses a string and returns the reversed value
   *
   * @param input the string to be reversed
   * @return a String
   */
  public static String reverse(String input) {

    StringBuilder sinput = new StringBuilder(input);
    StringBuilder sinput1 = sinput.reverse();
    String reverse = sinput1.toString();
    return reverse;
  }
Esempio n. 6
1
 /**
  * Returns any trailing period, comma, semicolon, or colon characters from the given string. This
  * method is useful when parsing raw HTML links, in which case trailing punctuation must be
  * removed. Note that only punctuation that is not previously matched is trimmed - if the input is
  * "http://example.com/page_(page)" then the trailing parantheses will not be trimmed.
  *
  * @param text The text from which trailing punctuation should be returned.
  * @return Any trailing punctuation from the given text, or an empty string otherwise.
  */
 private String extractTrailingPunctuation(String text) {
   if (StringUtils.isBlank(text)) {
     return "";
   }
   StringBuilder buffer = new StringBuilder();
   for (int i = text.length() - 1; i >= 0; i--) {
     char c = text.charAt(i);
     if (c == '.' || c == ';' || c == ',' || c == ':' || c == '(' || c == '[' || c == '{') {
       buffer.append(c);
       continue;
     }
     // if the value ends with ), ] or } then strip it UNLESS there is a matching
     // opening tag
     if (c == ')' || c == ']' || c == '}') {
       String closeChar = String.valueOf(c);
       String openChar = (c == ')') ? "(" : ((c == ']') ? "[" : "{");
       int pos = Utilities.findMatchingStartTag(text, i, openChar, closeChar);
       if (pos == -1) {
         buffer.append(c);
         continue;
       }
     }
     break;
   }
   if (buffer.length() == 0) {
     return "";
   }
   buffer = buffer.reverse();
   return buffer.toString();
 }
Esempio n. 7
1
 public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   int m = scanner.nextInt();
   assert 1 <= m && m <= 100 : "out of range, m: " + m;
   int s = scanner.nextInt();
   assert 0 <= s && s <= 900 : "out of range, s: " + s;
   if (s > 9 * m || (s == 0 && m > 1)) {
     System.out.println("-1 -1");
     return;
   }
   if (m == 1 && s == 0) {
     System.out.println("0 0");
     return;
   }
   StringBuilder sb = new StringBuilder();
   int l = 0;
   for (int i = 0; i < m; i++) {
     int d = (s >= 9) ? 9 : s;
     sb.append(d);
     s -= d;
     if (d != 0) {
       l = i;
     }
   }
   String large = sb.toString();
   if (sb.charAt(m - 1) == '0') {
     sb.setCharAt(l, (char) (sb.charAt(l) - 1));
     sb.setCharAt(m - 1, '1');
   }
   String small = sb.reverse().toString();
   System.out.printf("%s %s", small, large);
 }
 public static void main(String[] args) {
   String input = "AliveisAwesome";
   StringBuilder input1 = new StringBuilder();
   input1.append(input);
   input1 = input1.reverse();
   for (int i = 0; i < input1.length(); i++) System.out.print(input1.charAt(i));
 }
  public static String reverse_hash(long hash) {

    StringBuilder code = new StringBuilder(9);
    String letters = "acdegilmnoprstuw";

    int index = 0;

    // Since the hash is initialized with a value of 7 and then built up from there, we iterate
    // and subtract values corresponding to characters until we hit the base case (7).
    while (hash > 7) {

      if (hash % 37 == 0) {

        // current hash value is a multiple of 37. We hit a character in the string.
        code.append(letters.charAt(index));
        index = 0;
        hash /= 37;

      } else {

        // Subtract by one and move to the next character.
        hash -= 1;
        index += 1;
      }
    }

    return code.reverse().toString();
  }
    @Override
    public CoinbaseSpotPriceHistory deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

      final List<CoinbaseHistoricalSpotPrice> historicalPrices =
          new ArrayList<CoinbaseHistoricalSpotPrice>();

      // If there is a better way to get to the actual String returned please replace this section.
      final Reader reader = (Reader) ctxt.getParser().getTokenLocation().getSourceRef();
      reader.reset();
      final StringBuilder historyStringBuilder = new StringBuilder();
      for (int c = reader.read(); c > 0; c = reader.read()) historyStringBuilder.append((char) c);

      // Parse in reverse because they are inconsistent with the number of decimals for the rates
      // which makes it difficult to differentiate from the following year. Going in reverse
      // we can rely on the comma.
      final String entireHistoryString = historyStringBuilder.reverse().toString();
      final Matcher matcher = historicalRateStringPatternInReverse.matcher(entireHistoryString);
      while (matcher.find()) {
        final String rateString = new StringBuilder(matcher.group(1)).reverse().toString();
        final BigDecimal spotRate = new BigDecimal(rateString);
        final String timestampString = new StringBuilder(matcher.group(2)).reverse().toString();
        final Date timestamp = DateUtils.fromISO8601DateString(timestampString);

        final CoinbaseHistoricalSpotPrice historicalSpotPrice =
            new CoinbaseHistoricalSpotPrice(timestamp, spotRate);
        historicalPrices.add(historicalSpotPrice);
      }
      Collections.sort(historicalPrices, Collections.reverseOrder());
      return new CoinbaseSpotPriceHistory(historicalPrices);
    }
Esempio n. 11
1
 private static String prs(String str, boolean rotate) {
   StringBuilder val = new StringBuilder(str);
   for (int i = 0; i < val.length(); ) {
     int c = val.charAt(i);
     if (c < 48 || c > 57) {
       val.deleteCharAt(i);
     } else i++;
   }
   return (rotate ? val.reverse() : val).toString();
 }
Esempio n. 12
0
  /*
  	public static String spiltString(String value, int lineWidth, Paint p) {
  		if (TextUtils.isEmpty(value))
  			return null;
  		if (value.indexOf("\n") == -1 && p.measureText(value) <= lineWidth) {
  			return value;
  		}
  		String rValue = "";
  		int spaceIndex = -1; // 表示最后出现的空格的位置
  		float drawWidth = 0; // 花字符串的实际宽度
  		float charWidth = 0; // 单个字符的宽度
  		int start = 0; // 起始位置
  		int end = 0; // 结束位置
  		String temp = "";
  		char[] chars = value.toCharArray(); // 转换为字符数组
  		char ch; // 单个的字符
  		for (int i = 0; i < chars.length; i++) {
  			ch = chars[i];
  			if (ch == ' ') // 如果是空格
  			{
  				spaceIndex = i;
  				Log.i(Tag, "发现空格,index=" + i);
  			} else if (ch == '\n') // 有换行字符
  			{
  				end = i;
  				if (start == end) {
  					spaceIndex = -1;
  					drawWidth = 0;
  					rValue += "\n";
  					continue;
  				} else {
  					end = i;
  					spaceIndex = -1;
  					temp = value.substring(start, end);
  					rValue += temp + "\n";

  					start = end;
  					drawWidth = 0;
  					continue;
  				}
  			}
  			charWidth = p.measureText(chars, i, 1); // 计算单个字符的宽度

  			if (drawWidth + charWidth >= lineWidth) // 如果加起来的宽度大于区域的宽度
  			{
  				if (spaceIndex != -1) // 如果有空格
  				{

  					end = i = spaceIndex;
  					temp = value.substring(start, end);
  					rValue += temp + "\n";

  					start = end;
  					spaceIndex = -1;
  				} else // 如果最近没有空格
  				{

  					end = i = i - 1;
  					temp = value.substring(start, end);
  					rValue += temp + "\n";

  					start = end;
  				}
  				drawWidth = 0.0f;

  			} else {

  				drawWidth += charWidth; // 如果小的话累加
  			}
  		}
  		if (start != -1) {
  			if (start <= value.length()) {
  				if (start == end) {
  					end = value.length();
  					temp = value.substring(start, end);

  					rValue += temp + "\n";
  				}
  			}
  		}
  		return rValue;
  	}
  */
  public static String MyTestBidi(String value, boolean isNeedreverse) {

    // value = reverseStrs(value); // 先颠倒
    int start = -1, end = -1;
    boolean isStarting = false;

    List<Integer> idcollaction = new ArrayList<Integer>();
    int index1 = 0, index2 = 0;
    for (int i = 0; i < value.length(); i++) {
      if (!IsUyExChar(value.charAt(i))) {
        isStarting = true;
        idcollaction.add(i);

      } else {
        if (isStarting) {
          index1 = idcollaction.get(0);
          index2 = idcollaction.get(idcollaction.size() - 1);
          value = Inverted(value, index1, index2);
          idcollaction.clear();
          isStarting = false;
        }
      }
    }
    if (isStarting) {
      index1 = idcollaction.get(0);
      index2 = idcollaction.get(idcollaction.size() - 1);
      value = Inverted(value, index1, index2);
    }
    StringBuilder builder = new StringBuilder(value);
    if (isNeedreverse) return builder.reverse().toString();
    return builder.toString();
  }
Esempio n. 13
0
 public static String reverseStrs(String value) {
   if (value != null) {
     StringBuilder builder = new StringBuilder(value);
     return builder.reverse().toString();
   }
   return "";
 }
Esempio n. 14
0
  public String add(String a, String b) {
    StringBuilder result = new StringBuilder();

    Map<Character, Integer> alphabet = new HashMap<>();
    for (int i = 0; i < 10; i++) alphabet.put((char) ('0' + i), i);
    for (int i = 0; i < 26; i++) {
      alphabet.put((char) ('a' + i), i + 10);
      alphabet.put((char) ('A' + i), i + 10);
    }

    int aLength = a.length();
    int bLength = b.length();

    int tempMemory = 0;

    for (int i = 0; i < aLength || i < bLength; i++) {
      char tempA = (i < aLength) ? a.charAt(aLength - 1 - i) : '0';
      char tempB = (i < bLength) ? b.charAt(bLength - 1 - i) : '0';

      int sum = alphabet.get(tempA) + alphabet.get(tempB) + tempMemory;
      if (sum < 36) {
        result.append(convertFromInt(sum));
        tempMemory = 0;
      } else {
        result.append(convertFromInt(sum % 36));
        tempMemory = 1;
      }
    }
    if (tempMemory == 1) result.append('1');

    return result.reverse().toString();
  }
 /** @param args the command line arguments */
 public static int reverse(int num) {
   int reverse = 0;
   StringBuilder sb = new StringBuilder(((Integer) num).toString());
   String rev = sb.reverse().toString();
   reverse = Integer.parseInt(rev);
   return reverse;
 }
Esempio n. 16
0
  public String addBinary(String a, String b) {
    if (a == null || a.length() == 0) return b;
    if (b == null || b.length() == 0) return a;

    StringBuilder sb = new StringBuilder();
    int pa = a.length() - 1;
    int pb = b.length() - 1;
    int flag = 0;
    while (pa >= 0 || pb >= 0) {
      int ca = 0, cb = 0;
      if (pa >= 0) {
        ca = a.charAt(pa) - '0';
        pa--;
      }
      if (pb >= 0) {
        cb = b.charAt(pb) - '0';
        pb--;
      }
      int sum = ca + cb + flag;
      if (sum >= 2) {
        flag = 1;
        sb.append((sum - 2 == 1) ? '1' : '0');
      } else {
        flag = 0;
        sb.append((sum == 1) ? '1' : '0');
      }
    }
    if (flag == 1) sb.append('1');
    return sb.reverse().toString();
  }
Esempio n. 17
0
  // 两正数相减(注意对0的处理)
  private MyBigInteger positiveSubtract(final String sLeft, final String sRight) {
    String left = sLeft, right = sRight;
    boolean isNegative = isGreater(left, right) ? false : true;
    if (isNegative) {
      String temp = left;
      left = right;
      right = temp;
    }
    // 字符填充
    right = zeroPopulatedString(right, left.length() - right.length());

    StringBuilder result = new StringBuilder();
    int carryVal = 0; // 借位值
    for (int i = left.length() - 1; i >= 0; i--) { // 从低位开始处理
      int temp = (left.charAt(i) - '0') - (right.charAt(i) - '0') - carryVal; // 对应位相减(含借位值)
      result.append(
          (i == 0 && temp == 0)
              ? ""
              : // 最高位为0时,舍弃
              (temp >= 0 ? temp : 10 + temp)); // 其他情况下,当前位分两种情况
      carryVal = temp < 0 ? 1 : 0; // 更新借位值
    }
    return MyBigInteger.newInstance(
        (isNegative ? '-' : '+') + trimZeroPopulatedString(result.reverse().toString()));
  }
Esempio n. 18
0
  Tester(int N) {
    n = N;
    arr = new int[(int) Math.pow(2, n)];
    int bins;
    for (int i = 1; i < arr.length; i++) {
      arr[i] = i;
    }
    StringBuilder stb;
    for (int i = 1; i < arr.length; i++) {
      stb = new StringBuilder();
      bins = n - 1 - (int) (Math.log(i) / Math.log(2));
      for (int j = 1; j <= bins; j++) {
        stb.append('0');
      }
      stb.append(Integer.toBinaryString(i));
      stb.reverse();
      int num = Integer.valueOf(stb.toString(), 2);

      if (num < arr.length && i > num) {
        int k = arr[num];
        arr[num] = arr[i];
        arr[i] = k;
      }
    }
    System.out.println('\n');
  }
  public String getQueryPlanTree(final DbIterator physicalPlan) {
    int queryPlanDepth = calculateQueryPlanTreeDepth(physicalPlan) - 1;

    SubTreeDescriptor root = buildTree(queryPlanDepth, 0, physicalPlan, 0, 0);
    char[] buffer = new char[queryPlanDepth * (root.width + 1)];
    Arrays.fill(buffer, ' ');
    for (int i = 1; i <= queryPlanDepth; i++) buffer[i * (root.width + 1) - 1] = '\n';

    printTree(root, buffer, root.width + 1);
    StringBuilder sb = new StringBuilder();

    boolean ending = false;
    for (int i = buffer.length - 1; i >= 0; i--)
      if (buffer[i] == '\n') {
        sb.append(buffer[i]);
        ending = true;
      } else if (ending) {
        if (buffer[i] != ' ') {
          ending = false;
          sb.append(buffer[i]);
        }
      } else sb.append(buffer[i]);

    return sb.reverse().toString();
  }
Esempio n. 20
0
 public static String longToN36(long l, int length) {
   StringBuilder sb = longToNBuf(l, N36_CHARS);
   for (int i = sb.length(); i < length; i++) {
     sb.append('0');
   }
   return sb.reverse().toString();
 }
  public static void main(String[] args) {
    System.out.println("Starting Reverser. Enter strings to reverse, or type tiuq to quit.");

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    while (true) {
      // Display prompt
      System.out.print("<Reverser> ");

      // Read a line from the user
      try {
        String line = in.readLine();

        // Exit if we reach EOF, or user types "quit"
        if (line == null || line.equals("tiuq")) {
          break;
        } else {
          StringBuilder sb = new StringBuilder(line);
          System.out.println(sb.reverse());
        }
      } catch (IOException e) {
        System.out.println(e.getMessage());
      }
    }
  }
Esempio n. 22
0
  // 两正数相加
  private MyBigInteger positiveAdd(
      final String sLeft, final String sRight, final boolean isNegative) {
    String left = sLeft, right = sRight;
    // 字符填充
    int lengthDiff = Math.abs(left.length() - right.length());
    if (left.length() < right.length()) {
      left = zeroPopulatedString(left, lengthDiff);
    } else if (left.length() > right.length()) {
      right = zeroPopulatedString(right, lengthDiff);
    }

    StringBuilder result = new StringBuilder();
    int carryVal = 0; // 进位值
    for (int i = left.length() - 1; i >= 0; i--) { // 从低位开始处理
      int temp = left.charAt(i) - '0' + right.charAt(i) - '0' + carryVal; // 对应位相加(含进位值)
      if (i == 0) { // 最高位
        result
            .append(temp % 10) // 当前位
            .append((temp / 10) == 0 ? "" : temp / 10); // 最高位的进位值
      } else {
        result.append(temp % 10); // 当前位
        carryVal = temp / 10; // 进位值更新
      }
    }
    return MyBigInteger.newInstance(
        (isNegative ? '-' : '+') + trimZeroPopulatedString(result.reverse().toString()));
  }
Esempio n. 23
0
  protected final String tail(File file) throws FileNotFoundException, IOException {
    RandomAccessFile fileHandler = new RandomAccessFile(file, "r");
    long fileLength = file.length() - 1;
    StringBuilder sb = new StringBuilder();

    for (long filePointer = fileLength; filePointer != -1; filePointer--) {
      fileHandler.seek(filePointer);
      int readByte = fileHandler.readByte();

      if (readByte == 0xA) {
        if (filePointer == fileLength) {
          continue;
        } else {
          break;
        }
      } else if (readByte == 0xD) {
        if (filePointer == fileLength - 1) {
          continue;
        } else {
          break;
        }
      }

      sb.append((char) readByte);
    }

    String lastLine = sb.reverse().toString();
    return lastLine;
  }
Esempio n. 24
0
 public String addBinary(String a, String b) {
   //	    if(a.length()==0)
   //	    	return b;
   //	    if(b.length()==0)
   //	    	return a;
   StringBuilder sb = new StringBuilder();
   int count = 0;
   int i;
   int j;
   for (i = a.length() - 1, j = b.length() - 1; i >= 0 && j >= 0; i--, j--) {
     int avalue = a.charAt(i) - '0';
     int bvalue = b.charAt(j) - '0';
     int sum = avalue + bvalue + count;
     sb.append(sum % 2 + "");
     count = sum / 2;
   }
   if (i < 0) {
     while (j >= 0) {
       int sum = b.charAt(j) - '0' + count;
       sb.append(sum % 2 + "");
       count = sum / 2;
       j--;
     }
   } else {
     while (i >= 0) {
       int sum = a.charAt(i) - '0' + count;
       sb.append(sum % 2 + "");
       count = sum / 2;
       i--;
     }
   }
   if (count > 0) sb.append(count + "");
   return sb.reverse().toString();
 }
 /**
  * Convert a big-endian binary string to a little-endian binary string and also pads with zeros to
  * make it "BITS" length.
  *
  * <p>e.g. BITS=5 value==6 big-endian=110 little-endian=011 (pad) return=01100
  */
 private static final String toBinaryString(int value) {
   StringBuilder builder = new StringBuilder(Integer.toBinaryString(value));
   builder = builder.reverse();
   while (builder.length() < BITS) {
     builder.append('0');
   }
   return builder.toString();
 }
 private String getLastLine(Document doc) throws BadLocationException {
   StringBuilder lineBuffer = new StringBuilder();
   String c = null;
   for (int i = 1; !"\n".equals(c = getLastChar(doc, i)); i++) { // NOI18N
     lineBuffer.append(c);
   }
   return lineBuffer.reverse().append('\n').toString();
 }
 // time: O(lgN); space: O(lgN), N is the value of base10 number
 public String convert10To2(int num) {
   StringBuilder sb = new StringBuilder();
   while (num > 0) {
     sb.append(num % 2);
     num /= 2;
   }
   return sb.reverse().toString();
 }
 public String convertToTitle(int n) {
   StringBuilder sb = new StringBuilder();
   while (n > 0) {
     int m = (n - 1) % 26;
     sb.append((char) ('A' + m));
     n = (n - 1) / 26;
   }
   return sb.reverse().toString();
 }
Esempio n. 29
0
 public static String colToCharIndex(int column) {
   StringBuilder colFinal = new StringBuilder();
   while (column > 0) {
     int n = (column - 1) % 26;
     colFinal.append(LETTERS.charAt(n));
     column = (column - n - 1) / 26;
   }
   return colFinal.reverse().toString();
 }
Esempio n. 30
0
  String add(String a, String b) {

    int[] tmpA = convertToInt(a);
    int[] tmpB = convertToInt(b);
    int[] intA;
    int[] intB;
    int diff;
    int tmp = 0;

    StringBuilder output = new StringBuilder();

    if (tmpA.length > tmpB.length) { // making arrays of equal length

      diff = tmpA.length - tmpB.length;
      intB = addZeros(tmpB, diff);
      intA = tmpA;

    } else if (tmpA.length < tmpB.length) {

      diff = tmpB.length - tmpA.length;
      intA = addZeros(tmpA, diff);
      intB = tmpB;

    } else {

      intA = tmpA;
      intB = tmpB;
    }

    for (int i = intA.length - 1; i >= 0; i--) { // array addition

      if (intA[i] == 1 && intB[i] == 1 && tmp == 1) {

        tmp = 1;
        output.append('1');
        continue;

      } else if ((intA[i] == 1 && intB[i] == 1) || ((intA[i] == 1 || intB[i] == 1) && tmp == 1)) {

        tmp = 1;
        output.append('0');
        continue;

      } else {

        output.append(intA[i] ^ intB[i] ^ tmp);
        tmp = 0;
      }
    }

    if (tmp == 1) {
      output.append(tmp);
    }

    return output.reverse().toString();
  }