GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Merge pull request #1089 from shellhub/dev · pythonpeixun/Java@b0766bf

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • DataStructures/Stacks
    • DecimalToAnyUsingStack.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎DataStructures/Stacks/DecimalToAnyUsingStack.java‎

Copy file name to clipboard
+44Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package DataStructures.Stacks;
2+
3+
import java.util.Stack;
4+
5+
public class DecimalToAnyUsingStack {
6+
public static void main(String[] args) {
7+
assert convert(0, 2).equals("0");
8+
assert convert(30, 2).equals("11110");
9+
assert convert(30, 8).equals("36");
10+
assert convert(30, 10).equals("30");
11+
assert convert(30, 16).equals("1E");
12+
}
13+
14+
/**
15+
* Convert decimal number to another radix
16+
*
17+
* @param number the number to be converted
18+
* @param radix the radix
19+
* @return another radix
20+
* @throws ArithmeticException if <tt>number</tt> or <tt>radius</tt> is invalid
21+
*/
22+
private static String convert(int number, int radix) {
23+
if (radix < 2 || radix > 16) {
24+
throw new ArithmeticException(
25+
String.format("Invalid input -> number:%d,radius:%d", number, radix));
26+
}
27+
char[] tables = {
28+
'0', '1', '2', '3', '4',
29+
'5', '6', '7', '8', '9',
30+
'A', 'B', 'C', 'D', 'E', 'F'
31+
};
32+
Stack<Character> bits = new Stack<>();
33+
do {
34+
bits.push(tables[number % radix]);
35+
number = number / radix;
36+
} while (number != 0);
37+
38+
StringBuilder result = new StringBuilder();
39+
while (!bits.isEmpty()) {
40+
result.append(bits.pop());
41+
}
42+
return result.toString();
43+
}
44+
}

0 commit comments

Comments
0 (0)
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.