# Java Exercises: Sum of all the elements from all possible subsets of a set formed by first n natural numbers

## Java Basic: Exercise-193 with Solution

Write a Java program that accept an integer and find the sum of all the elements from all possible subsets of a set formed by first n natural numbers.

**Sample Solution:**

**Java Code:**

```
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input a positive integer: ");
int n = in .nextInt();
int result = (n * (n + 1) / 2) * (1 << (n - 1));
System.out.print("Sum of subsets of n is : " + result);
}
}
```

Sample Output:

Input a positive integer: 25 Sum of subsets of n is : 1157627904

**Flowchart: **

**Java Code Editor:**

**Company:**
Bloomberg

** Contribute your code and comments through Disqus.**

**Previous:** Write a Java program to rearrange the alphabets in the order followed by the sum of digits in a given string containing uppercase alphabets and integer digits (from 0 to 9).

**Next:** Write a Java program to find the all positions of a given number in a given matrix. If the number not found print ("Number not found!").

**What is the difficulty level of this exercise?**

Test your Programming skills with w3resource's quiz.

## Java: Tips of the Day

** How to remove leading zeros from alphanumeric text?**

Regex is the best tool for the job; what it should be depends on the problem specification. The following removes leading zeroes, but leaves one if necessary (i.e. it wouldn't just turn "0" to a blank string).

s.replaceFirst("^0+(?!$)", "")

The ^ anchor will make sure that the 0+ being matched is at the beginning of the input. The (?!$) negative lookahead ensures that not the entire string will be matched.

Test harness:

String[] in = { "01234", // "[1234]" "0001234a", // "[1234a]" "101234", // "[101234]" "000002829839", // "[2829839]" "0", // "[0]" "0000000", // "[0]" "0000009", // "[9]" "000000z", // "[z]" "000000.z", // "[.z]" }; for (String s : in) { System.out.println("[" + s.replaceFirst("^0+(?!$)", "") + "]"); }

Ref: https://bit.ly/2Qdcl8a

**Weekly Trends**- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises