using System; class BinToDec { static void Main(string[] args) { string binary = "101"; Console.WriteLine(BinaryToDecimal(binary)); // will return 5 } private static long BinaryToDecimal(string binary) { long decimalNum = 0; for (int i = binary.Length - 1, pow = 0; i >= 0; i--, pow++) { decimalNum += int.Parse(binary[i].ToString()) * (long)Math.Pow(2, pow); } return decimalNum; } }
Tag: how to
How to print list separated by comma in Java
import java.util.ArrayList; import java.util.stream.Collectors; public class CommaDelimeter { public static void main(String[] args) { ArrayList<Integer> collectNums = new ArrayList<Integer>(); collectNums.add(2); collectNums.add(9); collectNums.add(12); String joined = collectNums.stream() .map(Object::toString) .collect(Collectors.joining(", ")); System.out.println(joined); } }
How to generate all subsets of power set using bitwise mask in C#
namespace SubsetsOfSet { using System; using System.Collections.Generic; using System.Linq; class SubsetsOfSet { static void Main() { int[] nums = { 0, 1, 2 }; string[] fruits = {"apple", "peach", "starwberry"}; int b = nums.Length; int n = (int)Math.Pow(2, b); for (int num = 0; num < n; num++) { var subSet = new List<int>(); for (int bit = 0; bit <= b; bit++) { if ((num >> bit & 1) == 1) { subSet.Add(nums[bit]); } } Console.WriteLine("{{{0}}}", string.Join(", ", subSet.Select(i => fruits[i]))); } } } }
How to generate random integer in range in Java
import java.util.Random; public class RandomNumInRange { public static void main(String[] args) { int min = 10; int max = 20; Random rand = new Random(); int randNum = rand.nextInt((max - min) + 1) + min; System.out.print(randNum); } }
How to split by forward or/and back slash in Java using RegEx
public class MatchBackslashRegex { public static void main(String[] args) { String string = "Element1\\Element2"; String[] strArr = string.split("/\\\\"); System.out.println(strArr[0]); // returns Element1 } }
How to reverse String in Java
public class ReverseString { public static void main(String[] args) { String a = "Test"; String aReversed = new StringBuilder(a).reverse().toString(); System.out.println(aReversed); // returns tseT } }